package com.sheep.jiuyan.samllsheep.service;

import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.accessibility.AccessibilityEvent;

import com.sheep.gamegroup.model.entity.AppRecord;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.model.entity.TaskListen;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.util.List;

/**
 * Created by realicing on 2018/5/4.
 * realicing@sina.com
 */
public class MonitorAppService extends AccessibilityService {
    @Override
    public void onAccessibilityEvent(AccessibilityEvent accessibilityEvent) {
        TaskListen taskEty = SheepApp.getInstance().getTaskEty();
        if(taskEty == null) {//当前没有时长任务时不操作数据库
            return;
        }
        // 此方法是在主线程中回调过来的，所以消息是阻塞执行的
        // 获取包名
        CharSequence packageName = accessibilityEvent.getPackageName();
        CharSequence className = accessibilityEvent.getClassName();
        int eventType = accessibilityEvent.getEventType();
        List<CharSequence> textList = accessibilityEvent.getText();
        switch (eventType) {
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                LogUtil.println("MonitorAppService TYPE_WINDOW_STATE_CHANGED: " + " pkgName: " + packageName + " className: " + className + " source: " + ListUtil.getIndex(textList, 0));

                long curTime = System.currentTimeMillis();
                AppRecord appRecord = new AppRecord();
                appRecord.setType_id(eventType);
                appRecord.setClassName(className.toString());
                appRecord.setPackageName(packageName.toString());
                if(!textList.isEmpty())
                    appRecord.setTag(textList.get(0).toString());

                AppRecord lastAppRecord = SheepApp.getInstance().getLastAppRecord();
                long lastTime = SheepApp.getInstance().getLastTime();
                if(lastAppRecord != null && lastTime != 0)
                    lastAppRecord.setTime(lastAppRecord.getTime() + curTime - lastTime);
                if(lastAppRecord != null && TextUtils.equals(taskEty.getPackage_names(), packageName.toString()))
                    MyDbManager.getInstance().saveOrUpdate(lastAppRecord);

                SheepApp.getInstance().setLastTime(curTime);
                SheepApp.getInstance().setLastAppRecord(appRecord);
                break;
//            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
//                System.out.println("MonitorAppService TYPE_WINDOW_CONTENT_CHANGED: " + " packageName: " + packageName + " source: " + ListUtil.getIndex(textList, 0));
//                break;
//            case AccessibilityEvent.TYPE_VIEW_CLICKED:
//                System.out.println("MonitorAppService TYPE_VIEW_CLICKED: " + " pkgName: " + packageName + " className: " + className  + " source: " + ListUtil.getIndex(textList, 0));
//                break;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Jump2View.getInstance().clearAlertDialog();
        return super.onStartCommand(intent, flags, START_STICKY);
    }

    @Override
    public void onInterrupt() {
        Jump2View.getInstance().startAccessibility(getApplicationContext());
        LogUtil.println("MonitorAppService onInterrupt");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Jump2View.getInstance().startAccessibility(getApplicationContext());
        LogUtil.println("MonitorAppService onUnbind");
        return super.onUnbind(intent);
    }

    public static boolean isAccessibilitySettingsOn(Context mContext) {
        int accessibilityEnabled = 0;
        final String service = mContext.getPackageName() + "/" + MonitorAppService.class.getCanonicalName();
        // com.z.buildingaccessibilityservices/android.accessibilityservice.AccessibilityService
        try {
            accessibilityEnabled = Settings.Secure.getInt(mContext.getApplicationContext().getContentResolver(),
                    android.provider.Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
        }
        TextUtils.SimpleStringSplitter mStringColonSplitter = new TextUtils.SimpleStringSplitter(':');

        if (accessibilityEnabled == 1) {
            String settingValue = Settings.Secure.getString(mContext.getApplicationContext().getContentResolver(),
                    Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            // com.z.buildingaccessibilityservices/com.z.buildingaccessibilityservices.TestService
            if (settingValue != null) {
                mStringColonSplitter.setString(settingValue);
                while (mStringColonSplitter.hasNext()) {
                    String accessibilityService = mStringColonSplitter.next();

                    if (accessibilityService.equalsIgnoreCase(service)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
