package com.genlot.ninglottery.game;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.genlot.nativesdk.model.GameRuntimeAttr;
import com.genlot.nativesdk.sender.EventToken;
import com.genlot.nativesdk.sender.TCPSender;
import com.genlot.ninglottery.event.NewIssueEvent;
import com.genlot.ninglottery.model.GameIDSet;
import com.genlot.ninglottery.toolkit.LogTool;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

public class GameService extends Service {
    private long mSSQDrawTime, m3DDrawTime, m7LCDrawTime, mK3DrawTime;
    private long mSSQIssue, m3DIssue, m7LCIssue, mK3Issue;
    private boolean mLoadingSSQ, mLoading3D, mLoading7LC, mLoadingK3, isStop;
    private GameRuntimeAttr mSSQRuntimeAttr, m3DRuntimeAttr, m7LCRuntimeAttr, mK3RuntimeAttr;
    private boolean mConnectStatus = true;
    private ScheduledExecutorService executorService;
    private ScheduledFuture<?> scheduledFuture1, scheduledFuture2;

    @Override
    public void onCreate() {
        super.onCreate();
        refreshData();
        isStop = false;
        initScheduleTask();
    }

    private void refreshData() {
        mSSQRuntimeAttr = GameManager.getGameRuntime(GameIDSet.GAME_ID_SSQ);
        m3DRuntimeAttr = GameManager.getGameRuntime(GameIDSet.GAME_ID_3D);
        m7LCRuntimeAttr = GameManager.getGameRuntime(GameIDSet.GAME_ID_SLC);
        mK3RuntimeAttr = GameManager.getGameRuntime(GameIDSet.GAME_ID_K3);

        mSSQDrawTime = mSSQRuntimeAttr.mDrawTime;
        m3DDrawTime = m3DRuntimeAttr.mDrawTime;
        m7LCDrawTime = m7LCRuntimeAttr.mDrawTime;
        mK3DrawTime = mK3RuntimeAttr.mDrawTime;

        mSSQIssue = mSSQRuntimeAttr.mGameIssue;
        m3DIssue = m3DRuntimeAttr.mGameIssue;
        m7LCIssue = m7LCRuntimeAttr.mGameIssue;
        mK3Issue = mK3RuntimeAttr.mGameIssue;

        mLoadingSSQ = false;
        mLoading3D = false;
        mLoading7LC = false;
        mLoadingK3 = false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isStop = true;
        stopScheduleTask();
    }

    private void initScheduleTask() {
        if (executorService == null) {
            executorService = Executors.newScheduledThreadPool(3);
            scheduledFuture1 = executorService.scheduleAtFixedRate(() -> {
                try {
//                        checkNetAvailable();
                    checkTime();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, 0, 1, TimeUnit.SECONDS);

        }
    }

    private void stopScheduleTask() {
        if (scheduledFuture1 != null) {
            scheduledFuture1.cancel(true);
        }
        if (scheduledFuture2 != null) {
            scheduledFuture2.cancel(true);
        }
    }

//    private void checkNetAvailable() {
//        boolean mNetAvailable = AppTool.isNetworkAvalible(this);
//        //断网
//        if (!mNetAvailable && mConnectStatus) {
//            mConnectStatus = false;
//            LogTool.logE(LogTool.tag(), "网络断开");
//        }
//        //重连
//        if (mNetAvailable && !mConnectStatus) {
//            LogTool.logE(LogTool.tag(), "网络重连,再次登录");
//            reLogin();
//        }
//    }
//
//    //重新登录
//    private void reLogin() {
//        String user = GameManager.getUser();
//        int mUser = Integer.parseInt(user);
//        String password = GameManager.getPassword();
//        int result = SystemNI.loginProcess(0, mUser, password);
//        if (result == 0) {
//            mConnectStatus = true;
//            TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1, gameList, reLoginSenderCallback);
//        } else {
//            LogTool.logI(LogTool.tag(), "重新登录失败 errCode = " + result);
//        }
//    }

    private void checkTime() {
        long curTime = System.currentTimeMillis() / 1000;
        if (mSSQDrawTime - curTime <= 0 && !mLoadingSSQ) {
            mLoadingSSQ = true;
            TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1, new int[]{GameIDSet.GAME_ID_SSQ},
                    getGameInfoCallback(GameIDSet.GAME_ID_SSQ));
        }
        if (m3DDrawTime - curTime <= 0 && !mLoading3D) {
            mLoading3D = true;
            TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1, new int[]{GameIDSet.GAME_ID_3D},
                    getGameInfoCallback(GameIDSet.GAME_ID_3D));
        }
        if (m7LCDrawTime - curTime <= 0 && !mLoading7LC) {
            mLoading7LC = true;
            TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1, new int[]{GameIDSet.GAME_ID_SLC},
                    getGameInfoCallback(GameIDSet.GAME_ID_SLC));
        }
        if (mK3DrawTime - curTime <= 0 && !mLoadingK3) {
            mLoadingK3 = true;
            TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1,  new int[]{GameIDSet.GAME_ID_K3},
                    getGameInfoCallback(GameIDSet.GAME_ID_K3));
        }
    }

    private TCPSender.SenderCallback getWinNumberCallback(int gameId, long gameIssue) {
        return new TCPSender.SenderCallback() {
            @Override
            public void onSenderSuccess(Bundle bundle) {
                ArrayList<String> winNumbers = bundle.getStringArrayList(EventToken.EVENT_KEY_RESULT_OBJECT);
                if (winNumbers != null) {
                    LogTool.logD("get win number = " + winNumbers.toString());
                }
                //新期数据
                TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1, new int[]{gameId},
                        getGameInfoCallback(gameId));
            }

            @Override
            public void onSenderFail(int code, String message) {
                LogTool.logD(gameId + message);
                try {
                    Thread.sleep( 60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!isStop) {
                    TCPSender.t101454QueryWinNumber(EventToken.T_GET_WIN_NUMBER, 1, gameId, gameIssue,
                            getWinNumberCallback(gameId, gameIssue));
                }
            }
        };
    }

    private TCPSender.SenderCallback getGameInfoCallback(int gameId) {
        return new TCPSender.SenderCallback() {
            @Override
            public void onSenderSuccess(Bundle bundle) {
                GameRuntimeAttr gameRuntime = GameManager.getGameRuntime(gameId);
                GameRuntimeAttr[] attr = (GameRuntimeAttr[]) bundle.getParcelableArray(EventToken.EVENT_KEY_RESULT_OBJECT);
                if (attr != null) {
                    for (GameRuntimeAttr anAttr : attr) {
                        if (gameId == anAttr.mGameID) {
                            if (gameRuntime.mGameIssue != anAttr.mGameIssue) {
                                GameManager.removeGameRuntime(gameId);
                                //新期游戏SN为0
                                anAttr.mGameSN = 0;
                                GameManager.appendGameRuntime(anAttr);
                                refreshData();
                                switch (gameId) {
                                    case GameIDSet.GAME_ID_SSQ:
                                        mLoadingSSQ = false;
                                        break;
                                    case GameIDSet.GAME_ID_3D:
                                        mLoading3D = false;
                                        break;
                                    case GameIDSet.GAME_ID_SLC:
                                        mLoading7LC = false;
                                        break;
                                    case GameIDSet.GAME_ID_K3:
                                        mLoadingK3 = false;
                                        break;
                                    default:
                                        break;
                                }
                                EventBus.getDefault().post(new NewIssueEvent(gameId));
                            } else {
                                try {
                                    if (gameId == GameIDSet.GAME_ID_K3) {
                                        Thread.sleep(2000);
                                    } else {
                                        //长周期隔5分钟取一次新期
                                        Thread.sleep(5 * 60 * 1000);
                                    }
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                if (!isStop) {
                                    TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1,
                                            new int[]{gameId}, getGameInfoCallback(gameId));
                                }
                            }
                        }
                    }
                }
            }

            @Override
            public void onSenderFail(int code, String message) {
                LogTool.logD(message);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!isStop) {
                    TCPSender.t101005QueryGameInfo(EventToken.T_QUERY_GAME_INFO, 1, new int[]{gameId},
                            getGameInfoCallback(gameId));
                }
            }
        };
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

}
