package com.genlot.ninglottery.module.login;

import android.os.Bundle;

import com.genlot.devicesdk.HWInfoTool;
import com.genlot.nativesdk.SystemNI;
import com.genlot.nativesdk.model.GameRuntimeAttr;
import com.genlot.nativesdk.model.HardwareInfo;
import com.genlot.nativesdk.model.SoftwareInfo;
import com.genlot.nativesdk.sender.EventToken;
import com.genlot.nativesdk.sender.TCPDownload;
import com.genlot.nativesdk.sender.TCPSender;
import com.genlot.ninglottery.application.LotteryApplication;
import com.genlot.ninglottery.base.BasePresenter;
import com.genlot.ninglottery.game.GameManager;
import com.genlot.ninglottery.model.GameIDSet;
import com.genlot.ninglottery.toolkit.AppTool;
import com.genlot.ninglottery.toolkit.LogTool;

import java.io.File;
import java.util.HashMap;

/**
 * @author ZhuYongKang
 * @description LoginPresenter
 * @date 2019/8/19
 */
public class LoginPresenter extends BasePresenter<ILoginView> {

    private int[] gameList = new int[]{GameIDSet.GAME_ID_SSQ, GameIDSet.GAME_ID_3D,
            GameIDSet.GAME_ID_SLC, GameIDSet.GAME_ID_K3};

    public void update() {
        TCPDownload.downloadApp((result, fileName) -> {
            if (result == 0) {
                //升级
                LotteryApplication.getInstance().getSystemTool().installApp(fileName);
            } else {
                getView().showToast("升级APK下载失败");
            }
        });
    }

    public void login(String userName, String Password) {
        int userID = Integer.parseInt(userName);
        getView().showLoading("登录中...");
        int result = SystemNI.loginProcess(0, userID, Password);
        if (result == 0) {
            t101025SyncTime();
        }else{
            getView().onLoginFailed(result);
        }
    }

    private void t101025SyncTime() {
        TCPSender.t101025SyncTime(EventToken.T_SYNC_TIME, 1, new TCPSender.SenderCallback() {
            @Override
            public void onSenderSuccess(Bundle bundle) {
                long time = bundle.getLong(EventToken.EVENT_KEY_RESULT_OBJECT);
                if (AppTool.setSystemTime(time * 1000)) {
                    LogTool.logI("设置系统时间成功");
                } else {
                    LogTool.logE("设置系统时间失败");
                }
                t101005QueryGameInfo();
            }

            @Override
            public void onSenderFail(int code, String message) {
                getView().dismissLoading();
                getView().showToast(message);
            }

        });
    }

    private void t101005QueryGameInfo() {
        TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1, gameList,
                new TCPSender.SenderCallback() {
                    @Override
                    public void onSenderSuccess(Bundle bundle) {
                        GameManager.clearGameRuntime();
                        GameRuntimeAttr[] attrs = (GameRuntimeAttr[]) bundle.getParcelableArray(EventToken.EVENT_KEY_RESULT_OBJECT);
                        if (attrs != null) {
                            for (GameRuntimeAttr attr : attrs) {
                                LogTool.logD("t101005QueryGameInfo:" + attr.toString());
                                attr.mGameName = GameManager.getGameName(attr.mGameID);
                                GameManager.appendGameRuntime(attr);
                            }
                        } else {
                            LogTool.logE("101005 get GameRuntimeAttr[] = null");
                        }
                        //取游戏数据成功后取游戏SN
                        t101022QueryGameSN();
                    }

                    @Override
                    public void onSenderFail(int code, String message) {
                        getView().dismissLoading();
                        getView().showToast(message);
                    }

                });
    }

    private void t101022QueryGameSN() {
        TCPSender.t101022QueryGameSN(EventToken.T_QUERY_GAME_SN, 1, gameList,
                new TCPSender.SenderCallback() {
                    @Override
                    public void onSenderSuccess(Bundle bundle) {
                        HashMap<Integer, String> snMaps = (HashMap<Integer, String>) bundle.getSerializable(EventToken.EVENT_KEY_RESULT_OBJECT);
                        if (snMaps != null && snMaps.size() != 0) {
                            for (int gameId : snMaps.keySet()) {
                                GameRuntimeAttr attr = GameManager.getGameRuntime(gameId);
                                if (attr != null) {
                                    String sn = snMaps.get(gameId) != null ? snMaps.get(gameId) : "0";
                                    LogTool.logD("t101022QueryGameSN:"+attr.mGameName + sn);
                                    attr.mGameSN = Long.parseLong(sn);
                                }
                            }
                        }
                        t101026QueryAccount();
                    }

                    @Override
                    public void onSenderFail(int code, String message) {
                        getView().dismissLoading();
                        getView().showToast(message);
                    }

                });
    }

    private void t101026QueryAccount() {
        TCPSender.t101026QueryAccount(EventToken.T_QUERY_ACCOUNT, 1,
                new TCPSender.SenderCallback() {
                    @Override
                    public void onSenderSuccess(Bundle bundle) {
                        double[] value = bundle.getDoubleArray(EventToken.EVENT_KEY_RESULT_OBJECT);
                        if (value != null) {
                            GameManager.setAccount(value);
                            LogTool.logI("t101026QueryAccount:" + (value[0] + value[1]));
                        }
                        //获取站地址信息
                        getStationAddress();
                        getView().onLoginSuccess();
                    }

                    @Override
                    public void onSenderFail(int code, String message) {
                        getView().dismissLoading();
                        getView().showToast(message);
                    }

                });
    }

    private void getStationAddress() {
        String stationFile = SystemNI.getDownloadPath() + TCPDownload.LOCAL_STATION_ADDRESS;
        LogTool.logD("StationPath:" + stationFile);
        File file = new File(stationFile);
        if (file.exists()) {
            String address = TCPDownload.readDownloadFile(stationFile);
            GameManager.setStationAddress(address);
        } else {
            TCPDownload.downloadStationAddress((result, fileName) -> {
                if(result == 0){
                    String address = TCPDownload.readDownloadFile(fileName);
                    GameManager.setStationAddress(address);
                }
            });
        }
    }


    /**
     * 构建硬件信息，准备上传服务器
     */
    private HardwareInfo buildHardwareInfo() {
        HardwareInfo info = new HardwareInfo();
        HWInfoTool hwInfoTool = LotteryApplication.getInstance().getHWInfoTool();
        LogTool.logD(hwInfoTool.getHardwareInfo());
        info.mCPU = hwInfoTool.getCPUInfo();
        info.mRamSize = hwInfoTool.getRAMInfo();
        return info;
    }

    private void t101013UploadHardwareInfo(HardwareInfo info) {
        TCPSender.t101013UploadHardwareInfo(EventToken.T_UPLOAD_HARDWARE_INFO, 1, info,
                new TCPSender.SenderCallback() {
                    @Override
                    public void onSenderSuccess(Bundle bundle) {
                        //上传软件信息
                        t101014UploadSoftwareInfo();
                    }

                    @Override
                    public void onSenderFail(int code, String message) {
                        getView().dismissLoading();
                        getView().showToast(message);
                    }

                });
    }

    private void t101014UploadSoftwareInfo() {
        SoftwareInfo info = new SoftwareInfo();
        info.mAppVersion = AppTool.getAppVersionName(LotteryApplication.getInstance());
        info.mOSVersion = "5.1.1";
        TCPSender.t101014UploadSoftwareInfo(EventToken.T_UPLOAD_SOFTWARE_INFO, 1, info,
                new TCPSender.SenderCallback() {
                    @Override
                    public void onSenderSuccess(Bundle bundle) {
                        //获取站地址信息
//                        downLoadStationAddressInfo();
                    }

                    @Override
                    public void onSenderFail(int code, String message) {
                        getView().dismissLoading();
                        getView().showToast(message);
                    }

                });
    }


}
