package com.sunzee.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;

import com.sunzee.model.domain.Name;
import com.wuxiaolong.androidutils.library.LogUtil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.nio.charset.StandardCharsets;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * @Description 文件工具类
 */
public class FileUtil {
    public static String FILEPATH = "/storage/emulated/0/logdata/";
    public static final long SEVENT_DAYS = 604800000;

    private static String TAG = "FileUtil";

    /**
     * 获取指定目录内所有文件路径
     *
     * @param dirPath 需要查询的文件目录
     * @param _type   查询类型，比如mp3
     */
    public static File[] getAllFiles(String dirPath, String _type) {
        File f = new File(dirPath);
        if (!f.exists()) {//判断路径是否存在
            if (f.mkdir()) {
                getAllFiles(dirPath, _type);
            }
            return null;
        }
        File[] files = f.listFiles();
        if (files == null) {//判断权限
            return null;
        }
        for (File _file : files) {//遍历目录
            String _name = _file.getName();
            String filePath = _file.getAbsolutePath();//获取文件路径
            String fileName = _file.getName().substring(0, _name.length() - 4);//获取文件名
            LogUtil.d("LOGCAT", "fileName:" + fileName);
            LogUtil.d("LOGCAT", "FILEPATH:" + filePath);

        }
        return files;
    }

    /**
     * 判断文件是否为图片
     *
     * @param filePath 路径
     * @return
     */
    public static boolean isImageFile(String filePath) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        return options.outWidth != -1;
    }


    private final static String PREFIX_VIDEO = "video/";

    /**
     * Get the Mime Type from a File
     *
     * @param fileName 文件名
     * @return 返回MIME类型
     * thx https://www.oschina.net/question/571282_223549
     * add by fengwenhua 2017年5月3日09:55:01
     */
    private static String getMimeType(String fileName) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(fileName);
        return type;
    }

    /**
     * 根据文件后缀名判断 文件是否是视频文件
     *
     * @param fileName 文件名
     * @return 是否是视频文件
     */
    public static boolean isVedioFile(String fileName) {
        String mimeType = getMimeType(fileName);
        return !TextUtils.isEmpty(fileName) && mimeType.contains(PREFIX_VIDEO);
    }


    public static String getDeviceId() {
        String deviceId = "";
        File file = new File("/storage/emulated/0/mht/deviceid.txt");
        String fileContent = getFileContent(file);
        if (file != null && !TextUtils.isEmpty(fileContent)) {
            //如果存在 直接获取
            LogUtil.e(TAG, "getDeviceId: " + fileContent);
            deviceId = fileContent.trim();
        } else {
            //不存在 先生成再获取
            writeData();
            deviceId = getFileContent(file).trim();
        }
        int param = (int) SharedPreferencesUtils.getParam(Name.CONNECT_STATE, 10);
        if (param == 2) {
            return deviceId;
        } else {
            return "";
        }
    }

    private static void writeData() {
        String filePath = "/storage/emulated/0/mht/";
        String fileName = "deviceid.txt";
        String deviceId = "";
        long l = System.currentTimeMillis();
        Random random = new Random();
        String randomText = "";
        for (int i = 0; i < 4; i++) {
            int j = random.nextInt(1000);
            randomText = randomText + j;
        }
        deviceId = l + randomText;
        writeTxtToFile(deviceId, filePath, fileName);
    }

    // 将字符串写入到文本文件中
    private static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath + fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                LogUtil.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            LogUtil.e("TestFile", "Error on write File:" + e);
        }
    }

//生成文件

    private static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

//生成文件夹

    private static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            LogUtil.i("error:", e + "");
        }
    }


    //读取指定目录下的所有TXT文件的文件内容
    private static String getFileContent(File file) {
        String content = "";
        if (!file.isDirectory()) {  //检查此路径名的文件是否是一个目录(文件夹)
            if (file.getName().endsWith("txt")) {//文件格式为""文件
                BufferedReader buffreader = null;
                try {
                    buffreader = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8));
                    String line = "";
                    //分行读取
                    while ((line = buffreader.readLine()) != null) {
                        content += line + "\n";
                    }
                } catch (FileNotFoundException e) {
                    LogUtil.d("TestFile", "The File doesn't not exist.");
                } catch (IOException e) {
                    LogUtil.d("TestFile", e.getMessage());
                } finally {
                    try {
                        if (buffreader != null) {
                            buffreader.close();//关闭输入流
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return content;
    }

    //flie：要删除的文件夹的所在位置
    public static void deleteFile(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
//            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }

    /**
     * 获取文件后缀名
     *
     * @param fileName
     * @return
     */
    public static String getFileType(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    public static Bitmap getLoacalBitmap(String url) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流转化为Bitmap图片
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除超过7天的log文件
     */
    public static void pastDueLog() {
        File logFolder = new File(FILEPATH);
        if (logFolder.exists()) {
            File[] logFiles = logFolder.listFiles();
            for (File file : logFiles) {
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
                String nowDate = format.format(new Date(System.currentTimeMillis()));
                //LogUtil.d(TAG, "duibi: " + nowDate);
                try {
                    String replace = file.getName().replace("-" + FileUtil.getDeviceId() + ".txt", "");
                    LogUtil.d(TAG, "pastDueLog: " + replace);
                    Date dateFile = format.parse(replace);
                    Date dataNow = format.parse(nowDate);
                    long fileTime = dateFile.getTime();
                    long nowTime = dataNow.getTime();
                    if (nowTime - fileTime > SEVENT_DAYS) {
                        //如果超过7天，我们就进行删除指定的文件，否则就什么都不做。
                        //LogUtil.d(TAG, "duibi: "+fileTime);
                        //删除
                        file.delete();
                    }
                    //LogUtil.d(TAG, "duibi: "+dataNow);
                    //LogUtil.d(TAG, "duibi: " + file.getName());
                } catch (ParseException e) {
                    //604800000 7天
                    e.printStackTrace();
                }

            }
        }

    }

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getFileName() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String date = format.format(new Date(System.currentTimeMillis())) + "-" + FileUtil.getDeviceId() + ".txt";
        return date;
    }

    /**
     * 創建log文件
     */
    public static File createLogFile() {
        return makeFilePath(FILEPATH, FileUtil.getFileName());
    }
}
