package ai.pai.lensman.upgrade;

import android.os.AsyncTask;

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

import org.json.JSONObject;

import java.util.HashMap;

import ai.pai.lensman.base.BaseInteractor;
import ai.pai.lensman.utils.BoxUrlContainer;
import ai.pai.lensman.utils.HttpPostTask;


public class BoxUpgradeInteractor implements BaseInteractor {
    private HttpPostTask upgradeTask;
    private String bpversion_str;
    private BoxUpgradeListener listener;

    public BoxUpgradeInteractor(String bpversion_str, BoxUpgradeListener listener) {
        this.listener = listener;
        this.bpversion_str = bpversion_str;
    }

    @Override
    public void startJob() {
        cancelJob();
        HashMap<String, String> params = new HashMap<>();
        params.put("bpversion_str", bpversion_str);
        LogHelper.d("czy", "开始box升级任务");
        upgradeTask = new HttpPostTask(params) {

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d("czy", "box升级任务 box应答=" + response);
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        return true;
                    }
                } catch (Exception e) {
                    LogHelper.d("czy", "box升级任务 box应答异常 " + e);
                }
                return false;
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                listener.onBoxUpgrade(false);
                LogHelper.d("czy", "box升级任务失败");
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                listener.onBoxUpgrade(true);
                LogHelper.d("czy", "box升级任务成功");
            }
        };
        upgradeTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.SET_VERSION);
    }

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

    public interface BoxUpgradeListener {
        void onBoxUpgrade(boolean result);
    }

}
