package com.sheep.gamegroup.util;

import android.database.Cursor;

import com.sheep.gamegroup.model.entity.AppRecord;
import com.sheep.gamegroup.model.entity.AppUsage;
import com.sheep.gamegroup.model.entity.LoginUser;
import com.sheep.gamegroup.model.entity.NewbieTaskRecord;
import com.sheep.gamegroup.model.entity.SearchAppRecord;
import com.sheep.gamegroup.model.entity.SearchGameRecord;
import com.sheep.jiuyan.samllsheep.SheepApp;

import org.xutils.DbManager;
import org.xutils.ex.DbException;
import org.xutils.x;

import java.util.List;
import java.util.Locale;

/**
 * Created by ljy on 2018/3/17.
 */

public class MyDbManager {
    private static MyDbManager myDbManager = new MyDbManager();
    private final DbManager db;

    private MyDbManager() {
        DbManager.DaoConfig daoConfig = new DbManager.DaoConfig()
                .setDbName("sheep.db")
                .setDbVersion(2);
        db = x.getDb(daoConfig);
    }

    public static MyDbManager getInstance() {
        if (myDbManager == null) {
            myDbManager = new MyDbManager();
        }
        return myDbManager;
    }

    /**
     * 查找NewbieTaskRecord
     */
    public NewbieTaskRecord dbFindNewbieTaskRecord(String invitation_code) throws DbException {
        return db.findById(NewbieTaskRecord.class, invitation_code);
    }


    /**
     * 保存或更新表表
     */
    public void saveOrUpdate(Object o) {
        try {
            db.saveOrUpdate(o);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 删除表
     *
     * @param o
     */
    public void deleteTable(Class<?> o) {
        try {
            db.dropTable(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<AppRecord> getAppRecordList(String packageName) {
        try {
            return db.selector(AppRecord.class)
                    .where("package_name", "=", packageName)
                    .findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ListUtil.emptyList();
    }

    public void removeAppRecord() {
        try {
            db.dropTable(AppRecord.class);
//            String sql = String.format(Locale.CHINA,"delete from app_record where package_name in('%s')" , packageName);
//            Cursor cursor = db.execQuery(sql);
//            cursor.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public long getAppRunTime(String packageName) {
        try {
            //type_id 为32时对应 AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
//            Cursor cursor = db.execQuery(String.format(Locale.CHINA,"select sum(time) as all_time from app_record where package_name = '%s' and type_id = 32" , packageName));
//            Cursor cursor = db.execQuery(String.format(Locale.CHINA,"select sum(time) from app_record where package_name = '%s' and time > %d" , packageName, AutoTaskListUtil.getInstance().getFindTime()));
            Cursor cursor = db.execQuery(String.format(Locale.CHINA, "select sum(time) from app_record where package_name = '%s'", packageName));
            cursor.moveToFirst();
            long time = cursor.getLong(0);
            LogUtil.println("MyDbManager", "getAppRunTime", "runTime", "=", time);
            cursor.close();
            return time;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }
//    public long getAppRunTime(String packageName){
//        long time = 0;
//        List<AppRecord> list = getAppRecordList(packageName);
//        for (AppRecord appRecord : list) {
//            time += appRecord.getTime();
//        }
//        return time;
//    }

    public List<LoginUser> getAllLoginUser() {
        try {
            return db.selector(LoginUser.class)
                    .where("service_name", "=", SheepApp.getInstance().getConnectAddress().getName())
                    .findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ListUtil.emptyList();
    }

    public long getAppUsageTime(String packageName) {
        AppUsage appUsage = getAppUsage(packageName);
        return appUsage == null ? 0 : appUsage.getTotalTimeInForeground();
    }

    public AppUsage getAppUsage(String packageName) {
        try {
            return db.selector(AppUsage.class)
                    .where("package_name", "=", packageName)
                    .findFirst();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<SearchGameRecord> getAllSearchGameRecord(int type) {
        try {
            return db.selector(SearchGameRecord.class)
                    .where("type", "=", type)
                    .findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ListUtil.emptyList();
    }

    public List<SearchAppRecord> getAllSearchAppRecord() {
        try {
            return db.selector(SearchAppRecord.class)
                    .where("count", ">", 0)
                    .findAll();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ListUtil.emptyList();
    }

    public void hideSearchApp(SearchAppRecord item) {
        item.setCount(0);
        try {
            db.saveOrUpdate(item);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
