package cc.winboll.studio.libapputils.utils;

/**
 * @Author ZhanGSKen<zhangsken@qq.com>
 * @Date 2024/07/19 14:30:57
 * @Describe 文件工具类
 */
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import cc.winboll.studio.libappbase.LogUtils;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtils {

    public static final String TAG = "FileUtil";

    public static void shareJSONFile(Context context, String szShareFilePath) {
        Uri uri;
        File file = new File(szShareFilePath);
        uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
        /*if (Build.VERSION.SDK_INT >= 24) {//android 7.0以上
         uri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", file);
         } else {
         uri = Uri.fromFile(file);
         }*/
        Intent shareIntent = new Intent();    
        shareIntent.setAction(Intent.ACTION_SEND);    
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);    
        shareIntent.setType("application/json");

        shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        /*if (Build.VERSION.SDK_INT >= 24) {
         shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
         }*/

        // 设置分享的标题    
        context.startActivity(Intent.createChooser(shareIntent, "SHARE JSON"));  
    }

    public static void shareHtmlFile(Context context, String szHtmlFile) {
        File htmlFile = new File(szHtmlFile);
        Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", htmlFile);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(contentUri, "text/html");
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        context.startActivity(intent);
    }

    public static void copyAssetsToSD(Context context, String szSrcAssets, String szDstSD) {
        LogUtils.d(TAG, "copyAssetsToSD [" + szSrcAssets + "] to [" + szDstSD + "]");
        AssetManager assetManager = context.getAssets();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = assetManager.open(szSrcAssets);
            File outputFile = new File(szDstSD);
            outputStream = new FileOutputStream(outputFile);
            byte[] buffer = new byte[1024];
            int length = 0;
            while ((length = inputStream.read(buffer)) > 0) {
                outputStream.write(buffer, 0, length);
            }
            outputStream.flush();
            LogUtils.d(TAG, "copyAssetsToSD done.");
        } catch (IOException e) {
            LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    LogUtils.d(TAG, e.getMessage(), Thread.currentThread().getStackTrace());
                }
            }
        }
    }

    public static boolean copyFile(File srcFile, File dstFile) {
        if (!srcFile.exists()) {
            LogUtils.d(TAG, "The original file does not exist.");
        } else {
            try {
                // 源文件路径
                Path sourcePath = Paths.get(srcFile.getPath());
                // 目标文件路径
                Path destPath = Paths.get(dstFile.getPath());
                // 建立目标父级文件夹
                if (!dstFile.getParentFile().exists()) {
                    dstFile.getParentFile().mkdirs();
                }
                // 删除旧的目标文件
                if (dstFile.exists()) {
                    dstFile.delete();
                }
                // 拷贝文件
                Files.copy(sourcePath, destPath);
                LogUtils.d(TAG, "File copy successfully.");
                return true;
            } catch (Exception e) {
                LogUtils.d(TAG, e, Thread.currentThread().getStackTrace());
            }
        }
        return false;
    }
	

    /**
     * 读取文件为字节数组（Java 7 语法）
     */
    public static byte[] readByteArrayFromFile(String filePath) {
        FileInputStream fis = null;
        ByteArrayOutputStream bos = null;
        try {
            fis = new FileInputStream(filePath);
            bos = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            // 手动关闭流（Java 7 不支持 try-with-resources）
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 写入字节数组到文件（Java 7 语法）
     */
    public static boolean writeByteArrayToFile(byte[] data, String filePath) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(filePath);
            fos.write(data);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static String readStringFromFile(String filePath) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(filePath));
            StringBuilder content = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line).append(System.getProperty("line.separator"));
            }
            // 去除最后一个换行符（可选）
            if (content.length() > 0) {
                content.deleteCharAt(content.length() - 1);
            }
            return content.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
	
    public static boolean writeStringToFile(String content, String filePath, boolean append) {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(filePath, append));
            writer.write(content);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
