package com.gingersoft.gsa.cloud.base.utils;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;

import com.elvishew.xlog.XLog;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2018/11/16
 * 修订历史：2018/11/16
 * 描述：7.0 兼容
 * <files-path name="name" path="path" /> 对应getFilesDir()。
 * <cache-path name="name" path="path" /> 对应getCacheDir()。
 * <external-path name="name" path="path" /> 对应Environment.getExternalStorageDirectory()。
 * <external-files-path name="name" path="path" /> 对应getExternalFilesDir()。
 * <external-cache-path name="name" path="path" /> 对应getExternalCacheDir()。
 */
public class FileUtils {

    public static String FirstFolder = "GSACloud";//一级目录
    public static String file = "file";//文件文件夹
    public static String Image = "image";//图片文件夹
    public static String Log = "xLog";//日志存储
    public static String ActionLog = "actionLog";//操作日志
    public static String ErrorLog = "errorLog";//错误日志存储
    public static String APK = "Download";//安装包目录放在系统目录
    /*ALBUM_PATH取得机器的SD卡位置，File.separator为分隔符“/”*/
    public final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + File.separator + FirstFolder + File.separator;
    public final static String IMAGE_PATH = ALBUM_PATH + Image + File.separator;
    public final static String File_PATH = ALBUM_PATH + file + File.separator;
    public final static String LOG_PATH = ALBUM_PATH + Log + File.separator;
    public final static String ACTIONLOG_PATH = LOG_PATH + ActionLog + File.separator;
    public final static String ERRORLOG_PATH = LOG_PATH + ErrorLog + File.separator;
    public final static String APK_PATH = Environment.getExternalStorageDirectory() + File.separator + APK + File.separator;

    public final static String FILE_EXTENSION_SEPARATOR = ".";

    //操作日志單最大文件大小
    public final static int ACTION_MAX_SIZE = 1024 * 1024 * 5;
    //操作日志文件按照時間刪除
    public final static int ACTION_MAX_FILE_TIME = 1000 * 60 * 60 * 12;

    private FileUtils() {
        throw new AssertionError();
    }

    public static StringBuilder readFile(String filePath, String charsetName) {
        File file = new File(filePath);
        StringBuilder fileContent = new StringBuilder("");
        if (file == null || !file.isFile()) {
            return null;
        }
        BufferedReader reader = null;
        try {
            InputStreamReader is = new InputStreamReader(new FileInputStream(
                    file), charsetName);
            reader = new BufferedReader(is);
            String line = null;
            while ((line = reader.readLine()) != null) {
                if (!fileContent.toString().equals("")) {
                    fileContent.append("\r\n");
                }
                fileContent.append(line);
            }
            reader.close();
            return fileContent;
        } catch (IOException e) {
            throw new RuntimeException("IOException occurred. ", e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    throw new RuntimeException("IOException occurred. ", e);
                }
            }
        }
    }

    /**
     * 写文件
     *
     * @param
     * @return boolean 返回类型
     */
    public static boolean writeFile(String filePath, String content,
                                    boolean append) {
        if (TextUtils.isEmpty(content)) {
            return false;
        }

        FileWriter fileWriter = null;
        try {
            makeDirs(filePath);
            fileWriter = new FileWriter(filePath, append);
            fileWriter.write(content);
            fileWriter.close();
            return true;
        } catch (IOException e) {
            throw new RuntimeException("IOException occurred. ", e);
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    throw new RuntimeException("IOException occurred. ", e);
                }
            }
        }
    }

    /**
     * 创建文件的路径
     *
     * @param
     * @return boolean 返回类型
     */
    public static boolean makeDirs(String filePath) {
        String folderName = getFolderName(filePath);
        if (TextUtils.isEmpty(folderName)) {
            return false;
        }

        File folder = new File(folderName);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }

    public static String getFolderName(String filePath) {

        if (TextUtils.isEmpty(filePath)) {
            return filePath;
        }

        int filePosi = filePath.lastIndexOf(File.separator);
        return (filePosi == -1) ? "" : filePath.substring(0, filePosi);
    }

    /**
     * 写文本文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
     *
     * @param context
     */
    public static void write(Context context, String fileName, String content) {
        if (content == null)
            content = "";

        try {
            FileOutputStream fos = context.openFileOutput(fileName,
                    Context.MODE_PRIVATE);
            fos.write(content.getBytes());

            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取文本文件 文件保存在 /data/data/PACKAGE_NAME/files
     *
     * @param context
     * @param fileName
     * @return
     */
    public static String read(Context context, String fileName) {
        try {
            FileInputStream in = context.openFileInput(fileName);
            return readInStream(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String readInStream(FileInputStream inStream) {
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[512];
            int length = -1;
            while ((length = inStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, length);
            }

            outStream.close();
            inStream.close();
            return outStream.toString();
        } catch (IOException e) {
            XLog.tag("FileTest").d(e.getMessage());
        }
        return null;
    }

    /**
     * 创建文件
     *
     * @param folderPath
     * @param fileName
     * @return
     */
    public static File createFile(String folderPath, String fileName) {
        File destDir = new File(folderPath);
        if (!destDir.exists()) {
            destDir.mkdirs();
        }
        return new File(folderPath, fileName + fileName);
    }

    /*
     * 在SD卡上创建目录
     */
    public static File creatSDDir(String dirName) {
        File dir = new File(dirName);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dir;
    }

    /**
     * 获取文件大小
     *
     * @param filePath
     * @return
     */
    public static long getFileSize(String filePath) {
        long size = 0;

        File file = new File(filePath);
        if (file != null && file.exists()) {
            size = file.length();
        }
        return size;
    }

    /*
     * Java文件操作 获取文件扩展名
     * */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    /*
     * Java文件操作 获取不带扩展名的文件名
     * */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
}
