package com.kfzs.duanduan.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.kfzs.appstore.utils.restful.KFZSNetwork;
import com.kfzs.duanduan.KFZSApp;
import com.kfzs.duanduan.bean.CompareResult;
import com.kfzs.duanduan.bean.DownloadStatus;
import com.kfzs.duanduan.bll.UrlBll;
import com.kfzs.duanduan.datashare.KFZSDDContentSession;
import com.kfzs.duanduan.datashare.provider.download.DownLoadInfo;
import com.kfzs.duanduan.db.DataSave;
import com.kfzs.duanduan.event.BigEvent;
import com.kfzs.duanduan.event.EventTypes;
import com.kfzs.duanduan.proto.ApiRequestOuterClass;
import com.kfzs.duanduan.proto.GameOuterClass;
import com.kfzs.duanduan.proto.UserPlayedGameOuterClass;
import com.kfzs.duanduan.services.DownloadTaskService;
import com.kfzs.duanduan.utils.net.APIRequest;
import com.kfzs.duanduan.utils.net.APIRequestInstance;
import com.kfzs.duanduan.view.KFProgressButton;
import com.sheep.gamegroup.util.UMConfigUtils;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.utils.ClassFileHelper;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import okhttp3.Call;

import static com.kfzs.duanduan.services.DownloadTaskService.STATUS_ING;
import static com.kfzs.duanduan.view.KFProgressButton.STATUS.STATUS_FAIL;
import static com.kfzs.duanduan.view.KFProgressButton.STATUS.STATUS_FINISH;
import static com.kfzs.duanduan.view.KFProgressButton.STATUS.STATUS_INIT;
import static com.kfzs.duanduan.view.KFProgressButton.STATUS.STATUS_INSTALLING;
import static com.kfzs.duanduan.view.KFProgressButton.STATUS.STATUS_PAUSED;

/**
 * Created by HooRang on 2017/2/24.
 */
public abstract class GameStatusScanner {

    private static final String TAG = "GameStatusScanner";
    private Context mContext;
    private String strActivity;
    private KFProgressButton mTarget;
    private DownloadTaskService downloadTaskService;

    public GameStatusScanner(Context ctx, KFProgressButton target, String strFlag) {

        this.mContext = ctx;
        this.mTarget = target;
        this.strActivity = strFlag;
        this.downloadTaskService = new DownloadTaskService(ctx);
    }

    public void compare(GameOuterClass.Game model) {
        boolean isPkgInstalled = ApkUtils.getInstance().isPkgInstalled(model.getPackageName());
        int apkStatus = CompareResult.LT;
        if (isPkgInstalled) {
            apkStatus = ApkUtils.getInstance().comparePkgVersionCode(model.getPackageName(),
                    Integer.valueOf(model.getVersionCode()));
            switch (apkStatus) {
                case CompareResult.EQUALS:
                    mTarget.setText(R.string.open);
                    break;
                case CompareResult.GT:
                    mTarget.setText(R.string.update);
                    break;
                case CompareResult.LT:
                    mTarget.setText(R.string.download);
                    break;
            }
        } else {
            DownLoadInfo task = downloadTaskService.getDownloadTaskByUrl(model.getDownloadUrl());

            if (KFZSApp.getInstance().mRealDownloadUrl.containsValue(model.getDownloadUrl())) {

                Set<Map.Entry<String, String>> entries = KFZSApp.getInstance().mRealDownloadUrl.entrySet();
                Iterator<Map.Entry<String, String>> iterator = entries.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    String value = next.getValue();
                    if (TextUtils.equals(value, model.getDownloadUrl())) {
                        task = downloadTaskService.getDownloadTaskByUrl(next.getKey());
                        break;
                    }
                }
            }
            if (null != task) {
                switch (task.getMStatus()) {
                    case DownloadTaskService.STATUS_INIT:
                        break;
                    case DownloadTaskService.STATUS_ING:
                        mTarget.updateProgress(task.getMPercent() == null ? 0 : task.getMPercent());
                        mTarget.updateButtonUI(KFProgressButton.STATUS.STATUS_PROGRESSING, false);
                        break;
                    case DownloadTaskService.STATUS_PAUSE:
                        mTarget.updateProgress(task.getMPercent() == null ? 0 : task.getMPercent());
                        mTarget.updateButtonUI(KFProgressButton.STATUS.STATUS_PAUSED, false);
                        break;
                    case DownloadTaskService.STATUS_FAIL:
                        mTarget.setText(R.string.download_fail);
                        break;
                    case DownloadTaskService.STATUS_FINISH:
                        break;
                }
            }
        }

        //Bind values to button control
        mTarget.setTag(KFProgressButton.TAG_1, apkStatus);
        mTarget.setTag(KFProgressButton.TAG_2, model.getPackageName());
        mTarget.setTag(KFProgressButton.TAG_3, model.getDownloadUrl());
        mTarget.setTag(KFProgressButton.TAG_4, strActivity);
        mTarget.setTag(KFProgressButton.TAG_5, model.getGameName());
        mTarget.setTag(KFProgressButton.TAG_6, model.getIconImage());
        mTarget.setTag(KFProgressButton.TAG_7, TextUtils.isEmpty(model.getVersionCode()) ? "0" : model.getVersionCode());
        mTarget.setTag(KFProgressButton.TAG_8, model.getId());
    }

    public void addListener() {
        if (mTarget.hasOnClickListeners()) {
            //TODO 小刁，这里添加了应该不会有影响
            return;
        }
        if (!(mTarget.getTag(KFProgressButton.TAG_3) + "")
                .toLowerCase().startsWith("http")) {
            //小刁，这里还是强制处理下，免得服务器全是乱写些中文英文的。。。
            return;
        }
        mTarget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if(SpUtils.getClick(mContext)){
//                    SpUtils.saveClick(mContext, false);
//                }else{
//                    DialogAccountAbnormal.showDialog((Activity) mContext,null, "当前网络处于非WIFI状态，确定下载吗？", "取消", "确定" );
//                    return;
//                }
//                if(!DialogAccountAbnormal.showDialog((Activity) mContext,null, "当前网络处于非WIFI状态，确定下载吗？", "取消", "确定" )){
//                    return;
//                }
                if (null == downloadTaskService) {
                    downloadTaskService = new DownloadTaskService(mContext);
                }
                final String gameId = v.getTag(KFProgressButton.TAG_8).toString();
                final int versionCode = Integer.valueOf(v.getTag(KFProgressButton.TAG_7).toString());
                final String downloadUrl = v.getTag(KFProgressButton.TAG_3).toString();
                final String packageName = v.getTag(KFProgressButton.TAG_2).toString();
                final String gameName = v.getTag(KFProgressButton.TAG_5).toString();
                final String iconUrl = v.getTag(KFProgressButton.TAG_6).toString();
                int lResult = ApkUtils.getInstance().comparePkgVersionCode(packageName, versionCode);
                boolean isPkgInstalled = ApkUtils.getInstance().isPkgInstalled(packageName);
                if (isPkgInstalled && lResult == CompareResult.EQUALS) {//已经安装且版本相同
                    ApkUtils.openApplication(mContext, packageName);
                } else if (!downloadTaskService.isDownloadExists(downloadUrl) && !KFZSApp.getInstance().mRealDownloadUrl.containsValue(downloadUrl)) {
                    if (!preAddDownloadTaskValid(mContext,downloadTaskService)) {
                        return;
                    }
                    //发送红点信息
                    EventBus.getDefault().post(BigEvent.get().setEventTypes(EventTypes.TIPS_DOWN_ICON));
                    if (!TextUtils.isEmpty(downloadUrl) && !downloadUrl.endsWith(".apk")) {
                        String url = UrlBll.GameApi.DOWNLOAD_REDIRECT + "game_id=" + gameId + "&channel=" + DataSave.getInstance().getChannelName();
                        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                if (BuildConfig.DEBUG) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                if (!TextUtils.isEmpty(response)) {
                                    try {
                                        //{"Id":1,"GameId":23,"Channel":"tengxun","DownloadUrl":"http:\/\/7xp90a.com1.z0.glb.clouddn.com\/buliangren2_10303_haowan_3.0.1.apk"}
                                        JSONObject object = new JSONObject(response);
                                        String realUrl = object.optString("DownloadUrl");
                                        if (TextUtils.isEmpty(realUrl)) {
                                            Toast.makeText(mContext, "获取" + DataSave.getInstance().getChannelName() + "渠道下载地址失败", Toast.LENGTH_SHORT).show();
                                        } else {
                                            KFZSApp.getInstance().mRealDownloadUrl.put(realUrl, downloadUrl);
                                            startDownload(mContext, GameStatusScanner.this,downloadTaskService, gameId, versionCode, realUrl, packageName, gameName, iconUrl);
                                        }
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        });
                    } else {
                        startDownload(mContext, GameStatusScanner.this, downloadTaskService, gameId, versionCode, downloadUrl, packageName, gameName, iconUrl);
                    }
                } else {
                    targetBtnEventAction(downloadUrl);
                }
            }
        });
    }

    /**
     * 上传下载计数统计
     */
    public static void downCountUpdate(Context mContext, String gameid) {
        if (!TextUtils.isDigitsOnly(gameid)) {
            return;
        }
        HashMap<String, String> params = null;
        if (KFZSDDContentSession.getInstance().findOutHeadSession(mContext) != null
                && !TextUtils.isEmpty(KFZSDDContentSession.getInstance().findOutHeadSession(mContext).getToken())) {
            params = new HashMap<>();
            String token = KFZSDDContentSession.getInstance().findOutHeadSession(mContext).getToken();
            params.put(UrlBll.HeadParams.AUTHORIZATION, token);
        }


        APIRequest apiRequest = APIRequestInstance.postReq(TAG, UrlBll.AppStoreApi.GAME_COUNT_UPDATE+""+gameid,
                params, null, null, null);
        KFZSNetwork.addRequest(apiRequest);


        ApiRequestOuterClass.ApiRequest.Builder reqBuild = ApiRequestOuterClass.ApiRequest.newBuilder();
        UserPlayedGameOuterClass.UserPlayedGame.Builder builder
                = UserPlayedGameOuterClass.UserPlayedGame.newBuilder();
        builder.setGameId(Integer.valueOf(gameid));
        reqBuild.setUserPlayedGame(builder);

        APIRequest apiRequest2 = APIRequestInstance.postReq(TAG, UrlBll.AppStoreApi.GAME_PALYED,
                params, reqBuild.build().toByteArray(), null, null);
        KFZSNetwork.addRequest(apiRequest2);
    }


    public static void startDownload(Context context,GameStatusScanner scanner, DownloadTaskService downloadTaskService, String gameId, int versionCode, String downloadUrl, String packageName, String gameName, String iconUrl) {
        setUmengOnEvent(context,gameName);
        DownLoadInfo downloadInfo = addNewDownloadTask(downloadTaskService, gameName, downloadUrl, packageName, versionCode, iconUrl, Integer.parseInt(gameId),STATUS_ING);
        downloadTaskService.start(downloadInfo);
        if(scanner != null)
            scanner.onButtonClickReturnListener(downloadUrl, KFProgressButton.STATUS.STATUS_INSTALLING);
        //开始任务的时候，再发请求，不判断是否为首次添加等情况
        downCountUpdate(context,gameId);
    }

    //更新下载量；
    private void updateLoadNum(final String gameId) {
        final APIRequest request = APIRequestInstance.postReq(TAG, UrlBll.GameApi.GAME + gameId,
                new HashMap<String, String>(), null, null, null);
        KFZSNetwork.addRequest(request);
    }


    public static boolean preAddDownloadTaskValid(Context context,DownloadTaskService downloadTaskService ) {
        int currentDownloadTaskSize = downloadTaskService.getDownloadingTasksCount();
        if (currentDownloadTaskSize >= KFZSApp.MAX_DOWNLOAD_TASK_SIZE) {
            String strPrompt = String.format(context.getString(R.string.toast_download_task_out_of_rang), KFZSApp.MAX_DOWNLOAD_TASK_SIZE + "");
            Toast.makeText(context, strPrompt, Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    /**
     * 这里是点击按钮时，更新历史状态，也就是按钮的任务已经加入TASK后的点击处理
     *
     * @param downloadUrl
     * @return
     */
    private boolean targetBtnEventAction(final String downloadUrl) {

        boolean bPaused = false;
        DownLoadInfo downloadTask = null;
        if (KFZSApp.getInstance().mRealDownloadUrl.containsValue(downloadUrl)) {
            Set<Map.Entry<String, String>> entries = KFZSApp.getInstance().mRealDownloadUrl.entrySet();
            Iterator<Map.Entry<String, String>> iterator = entries.iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                String value = next.getValue();
                if (TextUtils.equals(value, downloadUrl)) {
                    downloadTask = downloadTaskService.getDownloadTaskByUrl(next.getKey());
                    break;
                }
            }
        } else {
            downloadTask = downloadTaskService.getDownloadTaskByUrl(downloadUrl);

        }
        if (null == downloadTask) {
            return false;
        }

        int percent = downloadTask.getMPercent() == null ? 0 : downloadTask.getMPercent();
        switch (downloadTask.getMStatus()) {
            case DownloadTaskService.STATUS_INIT:
                Log.d(TAG, "Still init status #" + downloadTask.getMDownloadUrl());
                onButtonClickReturnListener(downloadUrl, STATUS_INIT);
                break;
            case DownloadTaskService.STATUS_ING:
                bPaused = true;
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadTaskService.STATUS_PAUSE, percent, true);
                onButtonClickReturnListener(downloadUrl, STATUS_INSTALLING);
                break;
            case DownloadTaskService.STATUS_PAUSE:
                if (!preAddDownloadTaskValid(mContext,downloadTaskService)) {
                    return false;
                }
                bPaused = false;
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadTaskService.STATUS_ING, percent, false);
                onButtonClickReturnListener(downloadUrl, STATUS_PAUSED);
                break;
            case DownloadTaskService.STATUS_FAIL:
                bPaused = false;
                changeTaskPersistenceStatus(downloadTask.getMDownloadUrl(), DownloadTaskService.STATUS_INIT, 0, false);
                onButtonClickReturnListener(downloadUrl, STATUS_FAIL);
                break;
            case DownloadTaskService.STATUS_FINISH:

                if (new File(downloadTask.getMApkPath()).exists()) {
                    ApkUtils.installApk(mContext, downloadTask.getMApkPath());
                    onButtonClickReturnListener(downloadUrl, STATUS_FINISH);
                } else {
                    downloadTaskService.cancel(downloadTask);
                    downloadTaskService.deleteDownloadTaskByDownloadUrl(downloadUrl);
                    downloadTaskService.start(downloadTask);//重新下载
                }

                break;
            default:
                Log.d(TAG, "Unknown task status#" + downloadTask.getMStatus());
                onButtonClickReturnListener(downloadUrl, STATUS_INIT);
                break;
        }


        return bPaused;

    }


    /**
     * //TODO 小刁，这里以后改为返回info，这样能得到下载进度等信息，方便及时更新
     *
     * @param downloadUrl
     * @param status
     * @param percent
     * @param bPauseTask
     */
    private void changeTaskPersistenceStatus(String downloadUrl, int status, int percent, boolean bPauseTask) {
        boolean success = downloadTaskService.setDownloadTaskStatus(downloadUrl, status);
        DownLoadInfo downLoadInfo = downloadTaskService.getDownloadTaskByUrl(downloadUrl);
        if (success) {
            if (bPauseTask) {
                mTarget.setText(R.string.pausing);
                /****TODO 这里是暂时的解决方法，不是很完***/
                DownloadStatus event = new DownloadStatus();
                event.setDownloadUrl(downloadUrl);
                event.setStatus(DownloadTaskService.STATUS_PAUSE);
                EventBus.getDefault().post(event);
                /********************************/
                downloadTaskService.pause(downLoadInfo);
            } else {
                //这里应该改为安装中，而不是安装
                mTarget.setText(R.string.installing);
                downloadTaskService.start(downLoadInfo);
            }
        }
    }


    public static void setUmengOnEvent(Context mContext,String extInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("gameUnique", extInfo);
        UMConfigUtils.Event.GAME_DOWNLOAD.onEvent(map);
    }

    public static DownLoadInfo addNewDownloadTask(final DownloadTaskService downloadTaskService, String gameName, String downloadUrl,
                                                  String packageName, int versionCode, String iconUrl, int gameId, int state) {
        final DownLoadInfo task = new DownLoadInfo();
        task.setMIconUrl(iconUrl);
        task.setMGameName(gameName);
        task.setMDownloadUrl(downloadUrl);
        task.setMPackageName(packageName);
        task.setMVersionCode(versionCode);
        task.setMGameID(gameId);
        task.setMApkPath(ClassFileHelper.DIR+ File.separator +packageName + ClassFileHelper.FILE_SUFFIX);
        task.setMStatus(state);
        new Thread(new Runnable() {
            @Override
            public void run() {
                downloadTaskService.addDownloadTask(task);
            }
        }).start();
        return task;
    }

    public abstract void onButtonClickReturnListener(String downloadUrl, KFProgressButton.STATUS status);


}
