package com.virjar.g4proxy.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;

import com.virjar.g4proxy.Constant;
import com.virjar.g4proxy.utils.DeviceMessageUtil;
import com.virjar.g4proxy.utils.HttpClientUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Request;
import okhttp3.Response;
import top.wuhaojie.installerlibrary.AutoInstaller;

import static com.virjar.g4proxy.Constant.schedulerTAG;

public class SchedulerTaskService extends Service {

    //查询更新的间隔 （单位：分钟）
    public static final int updateInterval = 10;
    //上传设备信息的间隔  （单位： 分钟）
    public static final int reportInterval = 5;

    public static final String getNewestModifiedApkUrl = "http://www.scumall.com:5597/hermes/ModifiedApp/getNewestModifiedApk?appPackageName=";
    public static final String msgReportlUrl = "http://taskcenter.beta.qunar.com/api/phone/report";

    private long lastCheckUpdateTimestamp = 0;
    private long lastCheckReportTimestamp = 0;


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        checkAndRunTask();
        return null;
    }

    @Override
    public void onCreate() {
        registerAlarm();
        checkAndRunTask();
        super.onCreate();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        registerAlarm();
        checkAndRunTask();
        return START_STICKY;
    }


    private void checkAndRunTask() {
        Log.e(schedulerTAG, "checkAndRunTask");
        if (System.currentTimeMillis() - lastCheckUpdateTimestamp > (updateInterval * 1000 * 60) / 3) {
            runAppInstallTask();
        }else {
            lastCheckUpdateTimestamp = System.currentTimeMillis();
        }
        if (System.currentTimeMillis() - lastCheckReportTimestamp > (reportInterval * 1000 * 60) / 3){
            runReportMessageTask();
        }else {
            lastCheckReportTimestamp = System.currentTimeMillis();
        }
    }


    private void runReportMessageTask() {
        Log.e(schedulerTAG, "runUploadMessageTask");
        JSONObject deviceMessage = DeviceMessageUtil.getDeviceMessage(this);

        Request request = HttpClientUtils.postRequest(msgReportlUrl, deviceMessage);

        HttpClientUtils.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@javax.annotation.Nullable Call call, @javax.annotation.Nullable IOException e) {
                Log.e(Constant.TAG, "report device msg failed", e);
            }

            @Override
            public void onResponse(@javax.annotation.Nullable Call call, @javax.annotation.Nullable Response response) {
                try {
                    if (response != null) {
                        Log.e("report response",  response.body().string());
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    private void runAppInstallTask() {
        final String packageName = getApplicationInfo().packageName;
        Request request = HttpClientUtils.getRequest(getNewestModifiedApkUrl + packageName);

        HttpClientUtils.getClient().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@javax.annotation.Nullable Call call, @javax.annotation.Nullable IOException e) {
                Log.e(Constant.TAG, "get downloadUrl failed", e);
            }

            @Override
            public void onResponse(@javax.annotation.Nullable Call call, @javax.annotation.Nullable Response response) {
                try {
                    handleResponse(response, packageName);
                } catch (JSONException | PackageManager.NameNotFoundException | IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void doInstall(final String url) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Log.e(Constant.TAG, "installing");
                AutoInstaller installer = AutoInstaller.getDefault(SchedulerTaskService.this);
                installer.installFromUrl(url);
                installer.setOnStateChangedListener(new AutoInstaller.OnStateChangedListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onComplete() {

                    }

                    @Override
                    public void onNeed2OpenService() {
                        Toast.makeText(SchedulerTaskService.this, "请打开辅助功能服务", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void needPermission() {
                        Toast.makeText(SchedulerTaskService.this, "需要申请存储空间权限", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        });
    }

    public void handleResponse(Response response, String packageName) throws JSONException, PackageManager.NameNotFoundException, IOException {

        if (response.body() == null) {
            return;
        }
        String responseJson = response.body().string();

        Log.i(Constant.TAG, "app update config service response: " + responseJson);
        JSONObject jsonObject = new JSONObject(responseJson);
        jsonObject = jsonObject.optJSONObject("data");
        String downloadUrl = jsonObject.optString("downloadUrl");
        long versionCode = jsonObject.optLong("versionCode");

        Log.i(Constant.TAG, "downloadUrl: " + downloadUrl);
        Log.i(Constant.TAG, "up-to-date versionCode: " + versionCode);
        PackageInfo packageInfo = getPackageManager().getPackageInfo(packageName, PackageManager.GET_META_DATA);
        if (packageInfo.versionCode < versionCode) {
            Log.i(Constant.TAG, "the app need update,with download url: " + downloadUrl);
            doInstall(downloadUrl);
        }
    }

    private void registerAlarm() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int time = 1000 * 60 * Math.min(reportInterval, updateInterval);
        //获取系统开机至今所经历的毫秒
        long startTime = SystemClock.elapsedRealtime() + time;
        Intent intent = new Intent(this, SchedulerTaskService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
        if (alarmManager == null) {
            return;
        }
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, startTime, pendingIntent);
    }

}
