package com.sheep.gamegroup.util;

import android.net.Uri;
import android.text.TextUtils;

import com.sheep.jiuyan.samllsheep.BuildConfig;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by realicing on 2018/04/.
 * realicing@sina.com
 */
public class FileUtil {
    /**
     * 读取文件
     *
     * @param sFileName
     * @return
     */
    public static String readFile(String sFileName) {
        if (TextUtils.isEmpty(sFileName)) {
            return null;
        }

        final StringBuffer sDest = new StringBuffer();
        final File f = new File(sFileName);
        if (!f.exists()) {
            return null;
        }
        try {
            FileInputStream is = new FileInputStream(f);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            try {
                String data;
                while ((data = br.readLine()) != null) {
                    sDest.append(data);
                    sDest.append("\n");
                }
            } catch (IOException ex) {
                if (BuildConfig.DEBUG) {
                    ex.printStackTrace();
                }
            } finally {
                is.close();
                br.close();
            }
        } catch (Exception ex) {
            if (BuildConfig.DEBUG) {
                ex.printStackTrace();
            }
        } catch (OutOfMemoryError ex) {
            if (BuildConfig.DEBUG) {
                ex.printStackTrace();
            }
        }
        return sDest.toString().trim();
    }

    /**
     * 读取文件
     *
     * @param sFileName
     * @return
     */
    public static List<String> readLines(String sFileName) {
        if (TextUtils.isEmpty(sFileName)) {
            return null;
        }

        File f = new File(sFileName);
        return readLines(f);
    }

    /**
     * 读取文件
     *
     * @param f
     * @return
     */
    public static List<String> readLines(File f) {
        final List<String> list = new ArrayList<>();
        if (!f.exists()) {
            return null;
        }
        try {
            FileInputStream is = new FileInputStream(f);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));

            try {
                String data;
                while ((data = br.readLine()) != null) {
                    list.add(data);
                }
            } catch (IOException ex) {
                if (BuildConfig.DEBUG) {
                    ex.printStackTrace();
                }
            } finally {
                is.close();
                br.close();
            }
        } catch (Exception ex) {
            if (BuildConfig.DEBUG) {
                ex.printStackTrace();
            }
        } catch (OutOfMemoryError ex) {
            if (BuildConfig.DEBUG) {
                ex.printStackTrace();
            }
        }
        return list;
    }

    /**
     * 追加文件：使用FileWriter
     *
     * @param filePath
     * @param content
     */
    public static void addToFile(String filePath, String content) {
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(filePath, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 保存文件：使用FileWriter
     *
     * @param filePath
     * @param content
     */
    public static void saveFile(String filePath, String content) {
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(filePath, false);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 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;
    }

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

    /**
     * 获取文件名，带扩展名
     *
     * @param filename  前提是fileName前面一定没有/
     * @param defaultEx 默认的扩展
     * @return
     */
    public static String getFileName(String filename, String defaultEx) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename;
            } else {
                return filename + "." + defaultEx;
            }
        }
        return filename;
    }


    /**
     * 获取文件名称且不带扩展名
     *
     * @param filePath
     * @return
     */
    public static String getFileNameNoExFromPath(String filePath) {
        if ((filePath != null) && (filePath.length() > 0)) {
            Uri uri = Uri.parse(filePath);
            String lastPathSegment = uri.getLastPathSegment();
            if (lastPathSegment != null) {
                int dot = lastPathSegment.lastIndexOf('.');
                if (dot > 0) {
                    return lastPathSegment.substring(0, dot);
                }
                return lastPathSegment;
            }
        }
        return filePath;
    }


    /**
     * 递归删除文件或文件夹。
     *
     * @param pDir
     */
    public static void deleteFiles(File pDir) {
        deleteFiles(pDir, true);
    }

    /**
     * 递归删除文件或文件夹。
     *
     * @param pDir
     * @param isDeleteDir 是否删除本目录
     */
    public static void deleteFiles(File pDir, boolean isDeleteDir) {
        if (!pDir.exists() || Thread.interrupted())
            return;
        if (pDir.isFile()) {
            pDir.delete();
        } else if (pDir.isDirectory()) {
            File[] childFile = pDir.listFiles();
            if (isDeleteDir && childFile == null || childFile.length == 0) {
                pDir.delete();
                return;
            }
            for (File f : childFile) {
                deleteFiles(f);
            }
            pDir.delete();
        }
    }

}
