package com.mjsheng.myappstore.bean;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.util.Log;

import com.mjsheng.myappstore.database.DBHelper;
import com.mjsheng.myappstore.database.DBSqlBuilder;
import com.mjsheng.myappstore.utils.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class AppData {

    private static final String TAG = "--AppData--";
    private static final boolean DEBUG = false;



    //   更新搜索历史
    public static void upSearchData(Context context, String category, int search_time) {
        DBHelper helper = new DBHelper(context);
        Cursor cursor = null;
        try {
            cursor = helper.getCursor(DBSqlBuilder.APPLICATION_HISTORY,
                    " where category = '" + category + "'");
            ContentValues values = new ContentValues();
            if (cursor != null && cursor.moveToFirst()) {
                helper.deleteRow(DBSqlBuilder.APPLICATION_HISTORY,"category = '" + category + "'" );
            }

            values.put("category", category);
            values.put("search_time", search_time);
            helper.insertValues(DBSqlBuilder.APPLICATION_HISTORY, values);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            helper.close();
        }
    }
    //   删除搜索历史
    public static void deleteSearchData(Context context, String category) {
        DBHelper helper = new DBHelper(context);
        helper.deleteRow(DBSqlBuilder.APPLICATION_HISTORY,"category = '" + category + "'" );
    }

    //  获取搜索历史
    public static List<SearchBean> getSearchData(Context context) {
        List<SearchBean> infoList = new ArrayList<>();
        DBHelper helper = new DBHelper(context);
        Cursor cursor = null;
        SearchBean info;
        try {
            String sql  = "select * from " + DBSqlBuilder.APPLICATION_HISTORY + " order by search_time desc";
            cursor = helper.getCursorBySql(sql);
            while (cursor.moveToNext()) {
                info = new SearchBean();
                info.setCategory(cursor.getString(cursor.getColumnIndex("category")));
                info.setSearch_time(cursor.getInt(cursor.getColumnIndex("search_time")));
                infoList.add(info);
            }
            helper.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return infoList;
    }

    public static List<String> getConfigAppsPackageListWithoutMenuName(Context context, String sub_category) {
        List<String> appPackageList = new ArrayList<String>();
        DBHelper helper = new DBHelper(context);
        Cursor cursor = null;
        try {
            String sql = "select * from " + DBSqlBuilder.CONFIG_APP_TABLE
                    + " where sub_category <>'" + sub_category + "' order by order_id";
            cursor = helper.getCursorBySql(sql);
            String packageName = null;
            while (cursor.moveToNext()) {
                packageName = cursor.getString(cursor.getColumnIndex("pkg_name"));
                appPackageList.add(packageName);
                if (DEBUG)
                    Log.e(TAG, "getConfigAppsPackageListWithoutMenuName...menuName=" + sub_category + "; packageName=" + packageName);
            }
            if (cursor != null) {
                cursor.close();
            }
            helper.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        appPackageList.add("com.mjsheng.myappstore");
        return appPackageList;
    }


    public static List<String> getConfigAppsPackageList(Context context, String sub_category, boolean isFlag, boolean isThree) {
        List<String> appPackageList = new ArrayList<String>();
        DBHelper helper = new DBHelper(context);
        Cursor cursor = null;
        try {
            String sql = "select * from " + DBSqlBuilder.CONFIG_APP_TABLE
                    + " where sub_category='" + sub_category + "' order by order_id";
            cursor = helper.getCursorBySql(sql);
            String packageName = null;
            while (cursor.moveToNext()) {
                packageName = cursor.getString(cursor.getColumnIndex("pkg_name"));
                if (sub_category.equals(Utils.MENU_TONGBUJIAOCAI) || sub_category.equals(Utils.MENU_LY)) {
                    if (isThree) {
                        if (appPackageList.size() <= 3) {
                            appPackageList.add(packageName);
                        }
                    } else {
                        appPackageList.add(packageName);
                    }
                } else {
                    appPackageList.add(packageName);
                }
            }
            if (cursor != null) {
                cursor.close();
            }
            helper.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        if (isFlag) {
            if (sub_category.equals(Utils.MENU_TONGBUJIAOCAI) || sub_category.equals(Utils.MENU_LY)) {
                if (appPackageList.size() <= 3) {
                    appPackageList.add(Utils.STORE);
                }
            } else {
                appPackageList.add(Utils.STORE);
            }
        }
        return appPackageList;
    }

    public static List<String> getAllAppsPackageList(Context context) {
        List<String> appPackageList = new ArrayList<String>();
        DBHelper helper = new DBHelper(context);
        Cursor cursor = null;
        try {
            String sql = "select * from " + DBSqlBuilder.CONFIG_APP_TABLE;
            cursor = helper.getCursorBySql(sql);
            String packageName = null;
            while (cursor.moveToNext()) {
                packageName = cursor.getString(cursor.getColumnIndex("pkg_name"));
                appPackageList.add(packageName);
                if (DEBUG)
                    Log.e(TAG, "databaseAppPackageList..." + " packageName=" + packageName);
            }
            if (cursor != null) {
                cursor.close();
            }
            helper.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return appPackageList;
    }

    public static List<AppInfo> getSystemAppDatas(Context context) {
        List<AppInfo> systemAppList = new ArrayList<AppInfo>();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> mApps = context.getPackageManager().queryIntentActivities(mainIntent, 0);
        AppInfo appInfo = null;
        for (ResolveInfo app : mApps) {
            if (context.getPackageName().equals(app.activityInfo.packageName)) {
                continue;
            }
            appInfo = new AppInfo();
            appInfo.setPackageName(app.activityInfo.packageName);
            appInfo.setAppName(app.activityInfo.loadLabel(context.getPackageManager()).toString());
            appInfo.setIcon(app.activityInfo.loadIcon(context.getPackageManager()));

            systemAppList.add(appInfo);
        }
        return systemAppList;
    }



    public static List<AppInfo> getUserAppInfoList(Context context, String menuName) {
        List<String> databaseAppPackageList;
        if (menuName != null) {
            databaseAppPackageList = getConfigAppsPackageList(context, menuName, false, false);
        } else {
            databaseAppPackageList = getAllAppsPackageList(context);
        }

        List<AppInfo> hotAppsList = new ArrayList<AppInfo>();

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> mApps = context.getPackageManager().queryIntentActivities(mainIntent, 0);

        HashMap<String, ResolveInfo> mHashmap = new HashMap<String, ResolveInfo>();
        for (ResolveInfo resolveInfo : mApps) {
            if (mHashmap.containsKey(resolveInfo.activityInfo.packageName)) {
                continue;
            }
            mHashmap.put(resolveInfo.activityInfo.packageName, resolveInfo);
        }
        AppInfo appInfo = null;
        ResolveInfo resolveInfo = null;
        for (String app : databaseAppPackageList) {
            if (mHashmap.containsKey(app)) {
                resolveInfo = mHashmap.get(app);

                appInfo = new AppInfo();

                appInfo.setPackageName(resolveInfo.activityInfo.packageName);
                appInfo.setAppName(resolveInfo.activityInfo.loadLabel(
                        context.getPackageManager()).toString());
                appInfo.setIcon(resolveInfo.activityInfo
                        .loadIcon(context.getPackageManager()));

                hotAppsList.add(appInfo);
            }
        }

        return hotAppsList;
    }

    /**
     * @param context
     * @return
     */
    public static List<AppInfo> getSystemAppInfoList(Context context) {

        List<AppInfo> systemAppsList = new ArrayList<AppInfo>();

        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        List<ResolveInfo> mApps = context.getPackageManager().queryIntentActivities(mainIntent, 0);

        AppInfo appInfo = null;
        for (ResolveInfo resolveInfo : mApps) {

            appInfo = new AppInfo();

            appInfo.setPackageName(resolveInfo.activityInfo.packageName);
            appInfo.setAppName(resolveInfo.activityInfo.loadLabel(
                    context.getPackageManager()).toString());
            appInfo.setIcon(resolveInfo.activityInfo
                    .loadIcon(context.getPackageManager()));

            systemAppsList.add(appInfo);
        }
        return systemAppsList;
    }


    public static boolean isSystemApp(Context context, String pkg) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(pkg, 0);
            if ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
                //第三方应用
                return false;
            } else {
                //系统应用
                return true;
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return true;
        }
    }

    public static boolean isExistInDB(Context context, AppInfo appInfo) {
        DBHelper helper = new DBHelper(context);
        try {
            Cursor cursor = helper.getCursor(DBSqlBuilder.CONFIG_APP_TABLE,
                    "where pkg_name='" + appInfo.getPackageName() + "'");
            if (cursor != null && cursor.moveToFirst()) {
                return true;
            }
        } catch (Exception err) {
            Log.e(TAG, "isExistInDB...err.getmessage=" + err.getMessage());
            err.printStackTrace();
        } finally {
            helper.close();
        }
        return false;
    }


    public static boolean updateConfigApp(Context context, String category, String sub_category, String packageName) {

        DBHelper helper = new DBHelper(context);
        try {
            Cursor cursor = helper.getCursor(DBSqlBuilder.CONFIG_APP_TABLE,
                    " where pkg_name='" + packageName + "' and sub_category='" + sub_category + "'");
            Log.e(TAG, "updateConfigApp" + cursor.toString());
            if (cursor != null && cursor.moveToFirst()) {
                return true;
            }
            boolean result = false;
            ContentValues values = new ContentValues();
            values.put("pkg_name", packageName);
            values.put("category", category);
            values.put("sub_category", sub_category);
            result = helper.insertValues(DBSqlBuilder.CONFIG_APP_TABLE, values);
            return result;
        } catch (Exception err) {
            Log.e(TAG, "updateHotAppInfo...err.getmessage=" + err.getMessage());
            err.printStackTrace();
        } finally {
            helper.close();
        }
        return false;
    }


    public static String getConfigApp(Context context, String packageName) {
        String strings;
        DBHelper helper = new DBHelper(context);
        try {
            Cursor cursor = helper.getCursor(DBSqlBuilder.CONFIG_APP_TABLE,
                    " where pkg_name='" + packageName + "'");
            Log.e(TAG, "getDownloadApp" + cursor.toString());
            if (cursor != null && cursor.moveToFirst()) {
                strings = cursor.getString(cursor.getColumnIndex("category"));
                return strings;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (helper != null) {
                helper.close();
            }
        }
        return null;
    }


    public static boolean AddDownloadApp(Context context, String category, String sub_category, String packageName) {

        DBHelper helper = new DBHelper(context);
        try {
            Cursor cursor = helper.getCursor(DBSqlBuilder.DOWNLOADING_TABLE,
                    " where pkg_name='" + packageName + "' and sub_category='" + sub_category + "'");
            Log.e(TAG, "AddDownloadApp" + cursor.toString());
            if (cursor != null && cursor.moveToFirst()) {
                return true;
            }
            boolean result = false;
            ContentValues values = new ContentValues();
            values.put("category", category);
            values.put("sub_category", sub_category);
            values.put("pkg_name", packageName);
            result = helper.insertValues(DBSqlBuilder.DOWNLOADING_TABLE, values);
            return result;
        } catch (Exception err) {
            Log.e(TAG, "updateHotAppInfo...err.getmessage=" + err.getMessage());
            err.printStackTrace();
        } finally {
            helper.close();
        }
        return false;
    }

    public static String[] getDownloadApp(Context context, String packageName) {
        String[] strings;
        DBHelper helper = new DBHelper(context);
        try {
            Cursor cursor = helper.getCursor(DBSqlBuilder.DOWNLOADING_TABLE,
                    " where pkg_name='" + packageName + "'");
            Log.e(TAG, "getDownloadApp" + cursor.toString());
            if (cursor != null && cursor.moveToFirst()) {
                strings = new String[]{cursor.getString(cursor.getColumnIndex("category")), cursor.getString(cursor.getColumnIndex("sub_category"))};
                return strings;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (helper != null) {
                helper.close();
            }
        }
        return null;
    }


    public static void ChangedApp(Context context, String category, String sub_category, AppInfo appInfo) {

        DBHelper helper = new DBHelper(context);
        try {
            Cursor cursor = helper.getCursor(DBSqlBuilder.CONFIG_APP_TABLE,
                    " where pkg_name='" + appInfo.getPackageName() + "'");
            ;
            if (cursor != null && cursor.moveToFirst()) {
                return;
            }
            ContentValues values = new ContentValues();
            values.put("category", category);
            values.put("sub_category", sub_category);
            helper.updateValues(DBSqlBuilder.CONFIG_APP_TABLE, values, "pkg_name=?", new String[]{appInfo.getPackageName()});
        } catch (Exception err) {
            Log.e(TAG, "ChangedApp...err.getmessage=" + err.getMessage());
            err.printStackTrace();
        } finally {
            helper.close();
        }
    }

    public static void deleteDownloadApp(Context context, String packageName) {
        try {
            DBHelper helper = new DBHelper(context);
            try {
                String where = " pkg_name='" + packageName + "'";
                helper.deleteRow(DBSqlBuilder.DOWNLOADING_TABLE, where);

                helper.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (helper != null) {
                    helper.close();
                }
            }
        } catch (Exception err) {
            return;
        }
    }


    public static void deleteAppsByAppKey(Context context, String packageName) {
        try {
            DBHelper helper = new DBHelper(context);
            try {
                String where = " pkg_name='" + packageName + "'";
                helper.deleteRow(DBSqlBuilder.CONFIG_APP_TABLE, where);

                helper.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (helper != null) {
                    helper.close();
                }
            }
        } catch (Exception err) {
            return;
        }
    }

    public static void deleteAppsByTag(Context context, String sub_category) {
        try {
            DBHelper helper = new DBHelper(context);
            try {
                String where = " sub_category='" + sub_category + "'";
                helper.deleteRow(DBSqlBuilder.CONFIG_APP_TABLE, where);

                helper.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (helper != null) {
                    helper.close();
                }
            }
        } catch (Exception err) {
            return;
        }
    }

    public static void clearHotAppList(Context context) {
        try {
            DBHelper helper = new DBHelper(context);
            helper.deleteTable(DBSqlBuilder.CONFIG_APP_TABLE);
        } catch (Exception err) {
            return;
        }
    }



    public static AppInfo getAppInfoByPackageName(Context context, String packageName) {
        AppInfo appInfo = new AppInfo();
        if (packageName.equals("") || packageName == null) {
            AppData.clearHotAppList(context);
            return null;
        } else if (packageName.equals(Utils.STORE)) {
            appInfo.STORE_APP = true;
            appInfo.setAppName("添加");
            appInfo.setPackageName("appstore");
        } else {
            PackageManager pm = context.getPackageManager();
            try {
                ApplicationInfo applicationInfo = pm.getApplicationInfo(packageName, 0);
                appInfo.setAppName(applicationInfo.loadLabel(pm).toString());
                appInfo.setPackageName(packageName);
                appInfo.setIcon(applicationInfo.loadIcon(pm));
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        if (appInfo.getAppName() == null) {
            AppData.clearHotAppList(context);
        }
        return appInfo;
    }


}