package basic.update.present;

import android.content.Context;
import android.text.TextUtils;
import android.widget.Toast;

import com.wasu.module.IModule;
import com.wasu.module.http.HttpRequestModule;
import com.wasu.module.http.RequestParams;
import com.wasu.module.http.RequestParams.Method;
import com.wasu.module.http.RequestParams.RequestListener;
import com.wasu.module.log.WLog;

import java.util.Map;

import basic.api.API_UPDATE;
import basic.app.TvAppLike;
import basic.update.ApkPathManager;
import basic.update.UpdateUtil;
import basic.update.model.UpdateInfo;
import basic.update.task.IUpdateTaskListener;
import basic.update.task.RemindTask;
import basic.update.view.IUpdateView;

/**
 * 升级模块
 *
 * @author zhangrm@wasu.com
 */
public class UpdatePresent extends IModule implements IUpdatePresent{

    private static String TAG = "UpdatePresent";

    private static UpdatePresent mInstance;

    private String mPlatformInfo;    //平台信息mPlatformInfo

    /**
     * some info given from server
     */
    private IUpdateView iUpdateView = null;
    private String updateType = null;       //apk update type

    private UpdatePresent() {
    }

    public static UpdatePresent getInstance() {
        if (mInstance == null) {
            synchronized (UpdatePresent.class) {
                if (mInstance == null) {
                    mInstance = new UpdatePresent();
                }
            }
        }
        return mInstance;
    }

    /**
     * 初始化
     *
     * @param c
     * @param
     */
    public void init(Context c, String softwareInfo, String platformInfo) {
        if (isInited() || c == null || softwareInfo == null || platformInfo == null) {
            return;
        }

        setContext(c);

        mPlatformInfo = platformInfo;
        ApkPathManager.getsInstance().setSavePath(getContext().getFilesDir());

        setInited(true);
    }


    /**
     * 是否正在下载apk
     */
    private static boolean sIsFetchingApk = false;
    private static Toast sToast = null;
    private UpdateTaskListener sUpdatTaskListener =  new UpdateTaskListener();
    @Override
    public void checkWhetherNeedUpdate(IUpdateView updateView) {
        if (!isInited()) {
            return;
        }

        //init iUpdatView
        this.iUpdateView = updateView;

        if(!sIsFetchingApk){
            //UPDATE API
            RequestParams requestParam = new RequestParams(
                    Method.POST,
                    API_UPDATE.API_URL_UPDATE,
                    null,
                    UpdateUtil.composeRequestBody(getContext(),mPlatformInfo).getBytes(),
                    new RequestListener() {

                        @Override
                        public boolean onResponse(int errorCode, String data, int arg1,
                                                  Object extra) {
                            if (data == null) {
                                WLog.e(TAG,"update api return null ");
                                iUpdateView.showApkUpdateFailedUI();
                                return false;
                            }else{
                                WLog.i(TAG,"<<<<<<<<<< =<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
                                WLog.i(TAG,""+data);
                                WLog.i(TAG,"<<<<<<<<<< =<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ");
                            }

                            Map<String, String> response = UpdateUtil.parseResponse(data);
                            //save data returned from server
                            String apkDownloadUrl = response.get(UpdateInfo.UPDATEURL);
                            String newApkVersion = response.get(UpdateInfo.UPDATEVERSION);
                            String serverMsg = response.get(UpdateInfo.UPDATEINFO);
                            updateType = response.get(UpdateInfo.NEEDUPDATE);

                            //after parse data update APKPath info
                            ApkPathManager.getsInstance().setSaveName(new StringBuilder().append("version_").append(newApkVersion).toString());
                            ApkPathManager.getsInstance().setServerMsg(serverMsg);

                            WLog.i(TAG,"apkDownloadUrl = " + apkDownloadUrl);
                            WLog.i(TAG,"newApkVersion = " + newApkVersion);
                            WLog.i(TAG,"serverMsg = " + serverMsg);
                            WLog.i(TAG,"updateType = " + updateType);

                            if (TextUtils.equals(API_UPDATE.V_NOTUPDATE, updateType)) {
                                //do nothing
                                iUpdateView.showNoNeedUpdateUi();
                            } else if (TextUtils.equals(API_UPDATE.V_NOTIFYUPDATE, updateType)) {
                                Toast.makeText(TvAppLike.getContext(),"正在执行升级操作,请等待5分钟",Toast.LENGTH_LONG).show();
                                //give user choice chance
                                doFetchApkFile(apkDownloadUrl);
                            } else if (TextUtils.equals(API_UPDATE.V_FORCEUPDATE, updateType)) {
                                Toast.makeText(TvAppLike.getContext(),"正在执行升级操作,请耐心等待5分钟",Toast.LENGTH_LONG).show();
                                //do not ask user,just download apk directlly
                                doFetchApkFile(apkDownloadUrl);
                            }

                            return false;
                        }
                    });

            requestParam.setRequestPolicy(-1, -1);
            HttpRequestModule.getInstance().addTask(requestParam);
        }else{
            if(sToast == null){
                sToast =  Toast.makeText(TvAppLike.getContext(),"正在更新安装文件,请稍后......",Toast.LENGTH_LONG);
            }
            sToast.show();
        }
    }



    @Override
    public void doFetchApkFile(String apkUrl) {
        if (!TextUtils.isEmpty(apkUrl)) {
            WLog.i(TAG,"doFetchApkFile = " + apkUrl);
            //download apk file and save it
            new RemindTask(getContext(), sUpdatTaskListener).execute(apkUrl);
        }else{
            Toast.makeText(TvAppLike.getContext(),"apkUrl can not be found",Toast.LENGTH_LONG).show();
        }
    }

    /**
     * this listener should be an inner class , because it need to use params in outer class
     * in this class,we deal the logic after apk is downloaded
     */
    class UpdateTaskListener implements IUpdateTaskListener{

        @Override
        public void onTaskStart() {
            sIsFetchingApk = true;
            WLog.i(TAG,"Fetch APK task start");
        }

        @Override
        public void onTaskSuccess() {
            if (TextUtils.equals(API_UPDATE.V_NOTIFYUPDATE, updateType)) {
                //give user choice chance
                iUpdateView.showNotifyUpdateUI();
            } else if (TextUtils.equals(API_UPDATE.V_FORCEUPDATE, updateType)) {
                //do not ask user,just download apk directlly
                iUpdateView.showForceUpdateUI();
            }

            sIsFetchingApk = false;
            WLog.i(TAG,"Fetch APK task success");
        }

        @Override
        public void onTaskFailed() {
            sIsFetchingApk = false;
            WLog.i(TAG,"Fetch APK task failed");
            //apk download failed
            iUpdateView.showApkUpdateFailedUI();
        }
    }
}

