package ai.pai.client.utils;


import com.android.common.http.HttpUtils;
import com.android.hotpatch.utils.IPatchManager;

import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;

import ai.pai.client.BuildConfig;
import ai.pai.client.db.Preferences;

public class PatchManager extends IPatchManager{

    private String patchUrl;

    public PatchManager(){
        new File(Constants.APP_PATCH_DIR).mkdirs();
    }

    @Override
    protected String getPatchFileDownloadUrl(String patchConfigUrl) {
        if(patchConfigUrl.contains("?")){
            patchConfigUrl+="&platform=android";
        }else{
            patchConfigUrl+="?platform=android";
        }
        patchConfigUrl+="&version="+ BuildConfig.VERSION_NAME;
        patchConfigUrl+="&channel="+"guanwang";
        HashMap<String,String> httpParams = new HashMap<>();
        httpParams.put("src","0");
        String jsonStr = HttpUtils.doHttpPost(patchConfigUrl,httpParams);
        try{
            JSONObject response = new JSONObject(jsonStr);
            JSONObject data = response.getJSONObject("data");
            patchUrl = data.getString("patch_url");
            return patchUrl;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected boolean isNewPatchFound() {
        if(!Preferences.getInstance(context).getPatchUrl().equals(patchUrl)){
            new File(patchSavePath).delete();
            return true;
        }
        if(!new File(patchSavePath).exists()){
            return true;
        }
        return false;
    }

    @Override
    protected void afterPatchSuccess() {
        Preferences.getInstance(context).setPatchUrl(patchUrl);
    }
}
