package com.develop.food.base.utils;


import static com.develop.food.base.FoodCookBaseApp.application;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.format.Formatter;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;


import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

public class StringUtils {
    //room 食谱数据库版本号
    public static final int roomVersion = 3;

    //换行处理
    public static String getStringWrap(String str) {
        if (str == null) {
            return "";
        }
        if (str.contains("\n\n")) {
            return str;

        } else {
            return str.replace("\n", "\n\n");

        }
    }

    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }

    public  static String getUpdateTime(){
        String path = "system/media/cofa_update_recipe.txt";
        StringBuilder content = new StringBuilder();
        try {
            File file = new File(path);
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
            }
            reader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content.toString();
    }
    public static boolean doesUpdateTxtFileExist() {
        File file = new File("system/media/cofa_update_recipe.txt");
        return file.exists();
    }
    public static boolean doesFileExist(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }


    public static int getScreenSize(Context context) {
        DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
        float width = displayMetrics.widthPixels / displayMetrics.density;
        float height = displayMetrics.heightPixels / displayMetrics.density;


        double screenSize = Math.sqrt(width * width + height * height);  // 开平方
        Log.i("dimension", "宽度：" + width + "\n高度:" + height + "\n密度:" + displayMetrics.density);

        if (screenSize > 10.1) {
            // 超过10.1英寸，通常是大屏幕设备
            return 10;
        } else if (screenSize > 6.4) {
            // 6.4-10英寸，通常是7寸或8寸
            return 7;
        } else {
            // 6.4以下，通常是5寸或更小
            return 5;
        }
    }

    public static int getScreenSizeOne(Activity context) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        int w = metrics.widthPixels;//宽度
        int h = metrics.heightPixels;//高度
        int dpi = metrics.densityDpi;//每英寸所占像素 （dpi：dots per inch ）
        float xdpi = metrics.xdpi;//x方向上的dpi
        float density = metrics.density;//密度
        float scaledDensity = metrics.scaledDensity;
        Log.i("dimension", "宽度：" + w + "\n高度:" + h + "\nDPI:" + dpi + "\nxDPI:" + xdpi + "\n密度:" + density + "\nscaledDensity:" + scaledDensity);
        double screenSize = (Math.sqrt(w * w + h * h)) / xdpi;


        if (screenSize > 10.1) {
            // 超过10.1英寸，通常是大屏幕设备
            return 10;
        } else if (screenSize > 6.4) {
            // 6.4-10英寸，通常是7寸或8寸
            return 7;
        } else {
            // 6.4以下，通常是5寸或更小
            return 5;
        }
    }


    public static float getWindowsSize(Activity activity) {
        DisplayMetrics metrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        float widthInInches = metrics.widthPixels / metrics.xdpi;
        float heightInInches = metrics.heightPixels / metrics.ydpi;

        float screenSizeInInches = (float) Math.sqrt(Math.pow(widthInInches, 2) + Math.pow(heightInInches, 2));
        Log.i("dimension", "宽度：" + metrics.widthPixels
                + "\n高度:" + metrics.heightPixels + "\nx密度:"
                + metrics.xdpi + "\ny密度:" + metrics.ydpi);

        return screenSizeInInches;
    }

    public static int getWindowsScreen(Context context) {

        /**
         * 5寸屏  :  1280x720
         * 7寸屏   ：1024x600
         * 10寸   ： 1280*800
         * **/
        int width = getScreenSizeList(context)[0];
        int height = getScreenSizeList(context)[1];


//        Log.e("TAG 其他","width:"+getScreenSizeList(context)[0] + " height :"+getScreenSizeList(context)[1]);

        if (width == 1280 && height == 800) {
            return 10;
        } else if (width == 1024 && height == 600) {
            return 7;

        } else if (width == 1280 && height == 720) {
            return 5;
        } else {
            return 1;
        }

    }

    /**
     * 获取屏幕宽高
     */
    public static int[] getScreenSizeList(Context context) {
        int[] size = new int[2];
        WindowManager w = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display d = w.getDefaultDisplay();
        DisplayMetrics metrics = new DisplayMetrics();
        d.getMetrics(metrics);
        int widthPixels = metrics.widthPixels;
        int heightPixels = metrics.heightPixels;
        if (Build.VERSION.SDK_INT >= 17)
            try {
                Point realSize = new Point();
                Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
                widthPixels = realSize.x;
                heightPixels = realSize.y;
            } catch (Throwable ignored) {
            }
        size[0] = widthPixels;
        size[1] = heightPixels;
        return size;
    }


    public static String getFileMD5(String filePath) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
            InputStream fis = new FileInputStream(filePath);
            byte[] buffer = new byte[1024];
            int numRead = 0;
            while ((numRead = fis.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            fis.close();
            return toHexString(md5.digest());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String toHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }

    public static void unZip(String zipPath, String defPath) throws ZipException {

//        File zipFile = new File(zipPath);
//        ZipFile zip = new ZipFile(zipFile);
//        zip.extractAll(defPath);

        try {
            ZipFile zipFile = new ZipFile(zipPath);
            if (zipFile.isValidZipFile()) {
                zipFile.extractAll(defPath);
            } else {
                // zip文件无效
                Log.d("TAG jieya111", "zip文件无效");
            }
        } catch (ZipException e) {
            Log.d("TAG jieya111", "zip异常：" + e.getMessage().toString());

            // 处理异常
            e.printStackTrace();
        }

    }

    public static void copyFile(File srcDir, File destDir) throws IOException {
        if (!srcDir.exists()) {
            throw new IllegalArgumentException("TAG Source directory does not exist.");
        }
        if (!destDir.exists()) {
            destDir.mkdir();
            if (!destDir.exists()) {
                throw new IllegalStateException("TAG Destination directory could not be created.");
            }
        }
        for (File file : srcDir.listFiles()) {
            if (file.isFile()) {
                Log.d("TAG jieya000", "name:" + file.getName());
                File destFile = new File(destDir, file.getName());
                FileChannel inChannel = new FileInputStream(file).getChannel();
                FileChannel outChannel = new FileOutputStream(destFile).getChannel();
                try {
                    inChannel.transferTo(0, inChannel.size(), outChannel);
                } finally {
                    if (inChannel != null) {
                        inChannel.close();
                    }
                    if (outChannel != null) {
                        outChannel.close();
                    }
                }
            } else if (file.isDirectory()) {
                // This is a sub-directory, call copyDirectory() again
                copyFile(file, new File(destDir, file.getName()));
            }
        }
    }

    /**
     * 获得SD卡总大小
     *
     * @return
     */
    public static String getSDTotalSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(application, blockSize * totalBlocks);
    }

    /**
     * 获得sd卡剩余容量，即可用大小
     *
     * @return
     */
    public static String getSDAvailableSize() {
        File path = Environment.getExternalStorageDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(application, blockSize * availableBlocks);
    }

    /**
     * 获得机身内存总大小
     *
     * @return
     */
    public static String getRomTotalSize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long totalBlocks = stat.getBlockCount();
        return Formatter.formatFileSize(application, blockSize * totalBlocks);
    }

    /**
     * 获得机身可用内存
     *
     * @return
     */
    public static String getRomAvailableSize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        return Formatter.formatFileSize(application, blockSize * availableBlocks);
    }

    /**
     * * 获取android总运行内存大小
     * * @param context
     * *
     */
    public static long getTotalMemory(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }
            // 获得系统总内存，单位是KB
            int i = Integer.valueOf(arrayOfString[1]).intValue();
            //int值乘以1024转换为long类型
            initial_memory = new Long((long) i * 1024);
            localBufferedReader.close();
        } catch (IOException e) {
        }
        long memory = initial_memory / 1024 / 1024;//获取MB
        return memory;
    }


    /**
     * * 获取android当前可用运行内存大小
     * * @param context
     * *
     */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
// mi.availMem; 当前系统的可用内存
        return Formatter.formatFileSize(context, mi.availMem);// 将获取的内存大小规格化
    }

    /**
     * * 获取android总运行内存大小
     * * @param context
     * *
     */
    public static String getTotalMemoryString(Context context) {
        String str1 = "/proc/meminfo";// 系统内存信息文件
        String str2;
        String[] arrayOfString;
        long initial_memory = 0;
        try {
            FileReader localFileReader = new FileReader(str1);
            BufferedReader localBufferedReader = new BufferedReader(localFileReader, 8192);
            str2 = localBufferedReader.readLine();// 读取meminfo第一行，系统总内存大小
            arrayOfString = str2.split("\\s+");
            for (String num : arrayOfString) {
                Log.i(str2, num + "\t");
            }
            // 获得系统总内存，单位是KB
            int i = Integer.valueOf(arrayOfString[1]).intValue();
            //int值乘以1024转换为long类型
            initial_memory = new Long((long) i * 1024);
            localBufferedReader.close();
        } catch (IOException e) {
        }
        return Formatter.formatFileSize(context, initial_memory);// Byte转换为KB或者MB，内存大小规格化
    }


    /**
     * 方法名：getMemoryInfo()
     * 功    能：获取手机总存储,可用存储
     * 参    数：无
     * 返回值：long
     */
    public static long getMemoryInfo() {
        //获取到手机数据文件
        File path = Environment.getDataDirectory();
        //获取一个磁盘的状态对象
        StatFs stat = new StatFs(path.getPath());
        //获得一个扇区的大小
        long blockSizes = stat.getBlockSize();
        //获取扇区总数
        long totalBlocks = stat.getBlockCount();
        //获得可用扇区数量
        long availableBlocks = stat.getAvailableBlocks();
        //获得总存储空间,MB
        long memory = blockSizes * totalBlocks / 1024 / 1024;
        //获得总存储空间
        //String totalMemory = Formatter.formatFileSize(this, blockSizes * totalBlocks);
        //获得可用存储空间
        //String availableMemory = Formatter.formatFileSize(this, availableBlocks * blockSizes);
        return memory;
    }


    //处理数据库问题
    public static void modifyDatabase() {
        String DATABASE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/cofa_cooking/sqlite.db";
        SQLiteDatabase db = null;
        try {
            db = SQLiteDatabase.openDatabase(DATABASE_PATH, null, SQLiteDatabase.OPEN_READWRITE);

            // 获取当前版本
            int currentVersion = db.getVersion();
            Log.d("TAG SQL", "Current Database Version: " + currentVersion);

//            // 修改版本号
//            int newVersion = currentVersion + 1; // 你可以设置为任何你想要的版本号
////            db.setVersion(newVersion);
//            Log.d("TAG SQL", "Updated Database Version to: " + newVersion);


//            //判断表里面是否有需要的字段
//            boolean res = checkColumnExists(db,"cc_dev_recipe","food_description");
//            Log.d("TAG SQL", "cc_dev_recipe --- food_description :" + res);
//            boolean  issdas = checkColumnExists(db,"cc_dev_recipe","issdas");
//            Log.d("TAG SQL", "cc_dev_recipe --- issdas :" + issdas);


            if (currentVersion < roomVersion) {
                //如果sd卡数据库版本号小于room的版本的时候，需要设置版本后才能预打包数据库
                db.setVersion(roomVersion);
                //更新以后，需要在你添加字段的表加列名


                // 向表中插入新的 String 字段
                String tableName = "cc_dev_recipe"; // 替换为实际的表名
                String newClumnOne = "food_description"; // 替换为你想要添加的列名
                String newClumntwo = "chef_rec"; // 替换为你想要添加的列名
//
//            // SQLite 不支持直接判断列是否存在，通常需要尝试捕捉异常
                try {

                    //判断这个表有没有  food_description 字段
                    if (!checkColumnExists(db, tableName, newClumnOne)) {
                        String alterTableQuery = "ALTER TABLE " + tableName + " ADD COLUMN " + newClumnOne + " TEXT;";
                        db.execSQL(alterTableQuery);
                    }

                    //判断这个表有没有  chef_rec 字段
                    if (!checkColumnExists(db, tableName, newClumntwo)) {
                        String alterTwoTableQuery = "ALTER TABLE " + tableName + " ADD COLUMN " + newClumntwo + " TEXT;";
                        db.execSQL(alterTwoTableQuery);
                    }
                    Log.d("TAG SQL", "Added new column: " + newClumnOne);
                } catch (Exception e) {
                    Log.e("TAG SQL", "Error adding new column, it might already exist.", e);
                }


            } else {
                return;
            }


        } catch (Exception e) {
            Log.e("TAG SQL", "Error while modifying database", e);
        } finally {
            if (db != null) {
                db.close();
            }
        }
    }

    /**
     * 方法：检查表中某列是否存在
     *
     * @param db
     * @param tableName  表名
     * @param columnName 列名
     *                   存在返回真，不存在返回假
     * @return
     */
    public static boolean checkColumnExists(SQLiteDatabase db, String tableName, String columnName) {
        boolean result = false;
        Cursor cursor = null;

        try {
            cursor = db.rawQuery("select * from sqlite_master where name = ? and sql like ?"
                    , new String[]{tableName, "%" + columnName + "%"});
            result = null != cursor && cursor.moveToFirst();
        } catch (Exception e) {
            Log.e("TAG", "checkColumnExists..." + e.getMessage());
        } finally {
            if (null != cursor && !cursor.isClosed()) {
                cursor.close();
            }
        }

        return result;
    }


}
