package ai.pai.lensman.main;

import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.annotation.StringRes;

import com.android.common.executors.ThreadExecutor;
import com.android.common.http.HttpUtils;
import com.android.common.utils.LogHelper;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import ai.pai.lensman.BuildConfig;
import ai.pai.lensman.R;
import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.utils.BoxUrlContainer;
import ai.pai.lensman.utils.HttpPostTask;
import ai.pai.lensman.utils.UrlContainer;

/**
 * Created by chengzhenyu on 2017/4/4.
 */

public class SyncTimeInteractor implements BaseInteractor {
    private HttpPostTask timeSyncTask;
    private String lensmanId;
    private SyncTimeListener listener;
    private boolean isCancelled;

    public SyncTimeInteractor(String lensmanId, SyncTimeListener listener) {
        this.listener = listener;
        this.lensmanId = lensmanId;
    }

    @Override
    public void startJob() {
        cancelJob();
        isCancelled = false;
        HashMap<String, String> params = new HashMap<>();
        params.put("user_id", lensmanId);
        LogHelper.d("czy", "开始时间同步任务");
        timeSyncTask = new HttpPostTask(params) {

            int msgId = R.string.sync_time_box_error;

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d("czy", "时间同步任务 服务器应答=" + response);
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        JSONObject data = json.getJSONObject("data");
                        time = data.getString("time");
                    }
                } catch (Exception e) {
                    LogHelper.d("czy", "时间同步任务 服务器应答异常，采用本地时间 " + time);
                }
                try {
                    HashMap<String, String> boxParams = new HashMap<>();
                    boxParams.put("time", time);
                    if (isCancelled) {
                        return false;
                    }
                    if(BuildConfig.isTestMode){
                        return true;
                    }
                    String setTimeResp = HttpUtils.doHttpPost(BoxUrlContainer.SET_TIME_URL, boxParams);
                    LogHelper.d("czy", "时间同步任务 box设置时间应答=" + setTimeResp);
                    if (isCancelled) {
                        return false;
                    }
                    SystemClock.sleep(1000);
                    if (isCancelled) {
                        return false;
                    }
                    String boxResp = HttpUtils.doHttpPost(BoxUrlContainer.BOX_TIME_URL, null);
                    LogHelper.d("czy", "时间同步任务 box获取时间应答=" + boxResp);
                    if (isCancelled) {
                        return false;
                    }
                    JSONObject boxJson = new JSONObject(boxResp);
                    int boxStatus = boxJson.getInt("status");
                    if (boxStatus == 200) {
                        String boxTime = boxJson.getJSONObject("data").getString("time");
                        if (time.substring(0, 13).equals(boxTime.substring(0, 13))) {
                            return true;
                        }
                    }
                } catch (Exception e) {
                    LogHelper.e("czy", "时间同步任务发生异常=" + e);
                }
                return false;
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                listener.onTimeSync(false, msgId);
                LogHelper.d("czy", "时间同步失败");
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                listener.onTimeSync(true, 0);
                LogHelper.d("czy", "时间同步成功");
            }
        };
        timeSyncTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.SERVER_TIME_URL);
    }

    @Override
    public void cancelJob() {
        if (timeSyncTask == null) {
            return;
        }
        if (timeSyncTask.getStatus() == AsyncTask.Status.RUNNING) {
            timeSyncTask.cancel(true);
        }
        isCancelled = true;
        timeSyncTask = null;
    }

    public interface SyncTimeListener {

        void onTimeSync(boolean result, @StringRes int strId);
    }
}
