package com.tax.file.utils.token;

import com.tax.file.model.FileServer;
import com.tax.file.model.TkTaxUser;
import com.tax.file.model.token.TokenInfoModel;
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 TokenInfoModel getTokenCode(TkTaxUser tkTaxUser, FileServer fileServer) {
        TokenInfoModel tokenModel = null;
        try {
            tokenModel =  repeat(tkTaxUser,fileServer);
        } catch (IOException e) {
            logger.error(tkTaxUser.getTaxno() + "获取token连接超时");
        } catch (HttpException e) {
            logger.error(tkTaxUser.getTaxno() + "获取token无法连接");
        }
        return tokenModel;
    }

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

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

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

}
