package com.xypower.common;

import android.text.TextUtils;

import org.w3c.dom.Text;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.channels.Channels;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class FilesUtils {

    public static void copyFile(File source, File dest) throws IOException {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(source);
            output = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int bytesRead;
            while ((bytesRead = input.read(buf)) > 0) {
                output.write(buf, 0, bytesRead);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                if (input != null) input.close();
            } catch (Exception ex) {
            }
            try {
                if (output != null) output.close();
            } catch (Exception ex) {
            }
        }
    }

    public static void closeFriendly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (Exception ex) {
            }
            closeable = null;
        }
    }
    public static boolean DeleteFilesInPath(String path, long seconds) {
        File pathFile = new File(path);
        if (!pathFile.exists() || !pathFile.isDirectory()) {
            return false;
        }

        long ts = System.currentTimeMillis();
        long diff = 0;
        seconds *= 1000;

        List<File> files = new ArrayList<File>();

        for (File f : pathFile.listFiles()) {
            if (!f.isFile()) {
                continue;
            }
            diff = ts - f.lastModified();
            if (diff > seconds) {
                files.add(f);
            }
        }

        for (File f : files) {
            f.delete();
        }

        return true;
    }

    public static boolean DeleteFilesInPath(String path) {
        File pathFile = new File(path);
        if (!pathFile.exists() || !pathFile.isDirectory()) {
            return false;
        }

        for (File f : pathFile.listFiles()) {
            if (!f.isFile()) {
                continue;
            }

            f.delete();
        }

        return true;
    }

    public static byte[] int2Byte(int intValue) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[i] = (byte) (intValue >> 8 * (3 - i) & 0xFF);
            //System.out.print(Integer.toBinaryString(b[i])+" ");
            //System.out.print((b[i] & 0xFF) + " ");
        }
        return b;
    }

    /**
     * 4位字节数组转换为整型
     * @param b
     * @return
     */
    public static int byte2Int(byte[] b) {
        int intValue = 0;
        for (int i = 0; i < b.length; i++) {
            intValue += (b[i] & 0xFF) << (8 * (3 - i));
        }
        return intValue;
    }

    public static void writeTextFile(String path, String content) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            byte[] bytes = content.getBytes();
            fileOutputStream.write(bytes);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            closeFriendly(fileOutputStream);
        }
    }

    public static void writeFile(String path, byte[] bytes) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(path);
            fileOutputStream.write(bytes);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            closeFriendly(fileOutputStream);
        }
    }

    public static void ensureParentDirectoryExisted(String fileName) {
        File file = new File(fileName);
        try {
            File parentFile = file.getParentFile();
            if (!parentFile.exists()) {
                file.getParentFile().mkdirs();
            }
        } catch (Exception ex) {
        }
    }

    public static String readTextFile(String path) {
        FileInputStream fis = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = null;
        try {
            File file = new File(path);
            if (file.exists()) {
                boolean firstLine = true;
                fis = new FileInputStream(file);
                inputStreamReader = new InputStreamReader(fis, "UTF-8");
                bufferedReader = new BufferedReader(inputStreamReader);
                stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    if (!firstLine) {
                        stringBuilder.append("\n");
                    } else {
                        firstLine = false;
                    }
                    stringBuilder.append(line);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeFriendly(bufferedReader);
            closeFriendly(inputStreamReader);
            closeFriendly(fis);
        }

        return stringBuilder == null ? null : stringBuilder.toString();
    }

    public static String readTextFile(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
        StringBuilder stringBuilder = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            stringBuilder = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
                stringBuilder.append("\n");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeFriendly(bufferedReader);
            closeFriendly(inputStreamReader);
        }

        return stringBuilder == null ? null : stringBuilder.toString();
    }

    public static String[] splitLines(String output) {
        output = output.replaceAll("\r\n", "\n");
        output = output.replaceAll("\n\r", "\n");
        output = output.replaceAll("\r", "\n");

        return TextUtils.split(output,"\n");
    }

    public static byte[] readAllBytes(File file) {
        byte[] bytes = null;
        FileInputStream fileInputStream = null;
        try {
            bytes = new byte[(int)file.length()];
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytes);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            closeFriendly(fileInputStream);
        }

        return bytes;
    }

    public static byte[] readAllBytes(String file) {
        return readAllBytes(new File(file));
    }
}
