package com.tax.file.utils.token;

import com.tax.file.constants.FileConstants;
import com.tax.file.model.FileServer;
import com.tax.file.model.TkTaxUser;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class TokenFactory {

    protected static final Logger logger = LoggerFactory.getLogger(TokenFactory.class);

    private static int times = 1;

    public static String getTokenCode(TkTaxUser tkTaxUser, FileServer fileServer) {
        String token = null;
        try {
            token =  repeat(tkTaxUser,fileServer);
        } catch (IOException e) {
            logger.error(tkTaxUser.getTaxno() + "获取token连接超时");
        } catch (HttpException e) {
            logger.error(tkTaxUser.getTaxno() + "获取token无法连接");
        }
        return token;
    }

    private static TokenService getServce(FileServer fileServer){
        String tokenFrom = fileServer.getTokenFrom();
        switch (tokenFrom){
            case "1" : return GetTokenFromLocal.getInstance();
            default: return GetTokenFromTaxBureau.getInstance();
        }
    }

    private static String getToken(TkTaxUser tkTaxUser, FileServer fileServer) throws IOException, HttpException {
        return getServce(fileServer).getToken(tkTaxUser,fileServer);
    }

    private static String repeat(TkTaxUser tkTaxUser, FileServer fileServer) throws IOException, HttpException {
        String token = null;
        for(int i=0;i<times;i++){
            token = getToken(tkTaxUser,fileServer);
            if(StringUtils.isNotBlank(token)){
                return token;
            }
        }
        return token;
    }

}
