package com.sheep.jiuyan.samllsheep.service;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sheep.gamegroup.model.entity.AppRecord;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.TaskListen;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.LocationUtils;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.DeviceInfo;
import com.sheep.jiuyan.samllsheep.utils.G;

import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by realicing on 2018/5/8.
 * realicing@sina.com
 */
public class FloatService extends Service {

    private static final String TAG = "MainService";

    LinearLayout mFloatwindow;
    WindowManager.LayoutParams params;
    WindowManager mWm;

    ImageView floaticon;

    //状态栏高度.
    int statusBarHeight = -1;

    //不与Activity进行绑定.
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        createToucher();
        startTimer();
    }

    private void stopTimer() {
        if(subscription != null){
            subscription.unsubscribe();
        }
        subscription = null;
    }

    private Subscription subscription;
    private int count = 0;
    private void startTimer() {
        if(subscription == null)
            subscription = Observable.interval(1000, TimeUnit.MILLISECONDS)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            try {
                                checkTask();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            throwable.printStackTrace();
                        }
                    });
    }

    private void checkTask() {
        TaskListen taskEty = SheepApp.getInstance().getTaskEty();
        if(taskEty != null) {
            if(Jump2View.getInstance().startAccessibility(getApplication())){
                if(count > (BuildConfig.DEBUG ? 6 : 60)){//每过一分钟提交一次任务
                    count = 0;
                    if(TextUtils.isEmpty(taskEty.getPackage_names())){
                        if(BuildConfig.DEBUG)
                            G.showToast("没有包名，不能提交任务");
                        return;
                    }
                    String gps = LocationUtils.getInstance().getLongitudeLatitude(getApplicationContext());
                    JSONObject object = new JSONObject();
                    object.put("gps", gps);
                    long runTime = MyDbManager.getInstance().getAppRunTime(taskEty.getPackage_names());

                    AppRecord lastAppRecord = SheepApp.getInstance().getLastAppRecord();
                    if(lastAppRecord != null && TextUtils.equals(taskEty.getPackage_names(), lastAppRecord.getPackageName())){
                        runTime +=  System.currentTimeMillis() - SheepApp.getInstance().getLastTime();
                        SheepApp.getInstance().setLastTime(System.currentTimeMillis());
                    }
                    if(runTime <= 0){//时间小于等于0则不提交
                        return;
                    }

                    MyDbManager.getInstance().removeAppRecord();
                    LogUtil.println("MonitorAppService runTime = "+runTime);
                    object.put("task_time", runTime/1000);
                    object.put("release_task_id", taskEty.getRelease_task_id());
                    SheepApp.getInstance().getNetComponent().getApiService().commitAutoTask(object)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .subscribe(new SheepSubscriber<BaseMessage>(getApplicationContext()) {
                                @Override
                                public void onNext(BaseMessage baseMessage) {
                                    LogUtil.println("MonitorAppService baseMessage onNext "+ JSON.toJSONString(baseMessage));
                                    CommonUtil.getInstance().setTAskEnty(null);
                                }

                                @Override
                                public void onError(BaseMessage baseMessage) {
                                    LogUtil.println("MonitorAppService baseMessage onError "+JSON.toJSONString(baseMessage));
                                }
                            });
                }
                LogUtil.println("MonitorAppService count = "+count);
                count++;
                return;
            }
        }
        count = 0;
    }



    private void createToucher() {
        //赋值WindowManager&LayoutParam.
        params = new WindowManager.LayoutParams();
        if(mWm==null) {
            mWm = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        }
        //设置type.系统提示型窗口，一般都在应用程序窗口之上.
        //设置效果为背景透明.
        params.format = PixelFormat.RGBA_8888;
        //设置flags.不可聚焦及不可使用按钮对悬浮窗进行操控.
        params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
//
//        //设置窗口初始停靠位置.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //  大于等于 24 即为 7.0 及以上执行内容
            Log.e("qx", "7.0");
            params.type = WindowManager.LayoutParams.TYPE_PHONE; // 7.1
        } else {
            //  低于 24 即为 7.0 以下执行内容
            params.type = WindowManager.LayoutParams.TYPE_TOAST;   // 4.4
            Log.e("qx", "4.4");

        }

        params.gravity = Gravity.LEFT | Gravity.TOP;
        params.x = 0;
        params.y = DeviceInfo.dip2px(getApplicationContext(), 25);

        //设置悬浮窗口长宽数据.
        params.width = -2;
        params.height = DeviceInfo.dip2px(getApplicationContext(), 40f);

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局.
        mFloatwindow = (LinearLayout) inflater.inflate(R.layout.float_window, null);
        //添加toucherlayout
        Log.i(TAG, "toucherlayout-->left:" + mFloatwindow.getLeft());
        Log.i(TAG, "toucherlayout-->right:" + mFloatwindow.getRight());
        Log.i(TAG, "toucherlayout-->top:" + mFloatwindow.getTop());
        Log.i(TAG, "toucherlayout-->bottom:" + mFloatwindow.getBottom());

        //主动计算出当前View的宽高信息.
        mFloatwindow.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);

        //用于检测状态栏高度.
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = getResources().getDimensionPixelSize(resourceId);
        }
        Log.i(TAG, "状态栏高度为:" + statusBarHeight);

        //浮动窗口按钮.
        floaticon = mFloatwindow.findViewById(R.id.floate_icon);
        floaticon.setAlpha(0.0f);


    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            if (intent != null && intent.getBooleanExtra("isShow", true)) {
                if (mFloatwindow != null) {
                    mWm.addView(mFloatwindow, params);
                }
            } else {
                if (mFloatwindow != null)
                    mWm.removeViewImmediate(mFloatwindow);

            }
        } catch (Exception ignore) {
        }
        return super.onStartCommand(intent, flags, START_STICKY);
    }
    @Override
    public void onDestroy() {
        if (floaticon != null) {
            try {
                mWm.removeViewImmediate(mFloatwindow);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        stopTimer();
        super.onDestroy();
    }

}
