package com.casic.dcms.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.util.Log;

import com.casic.dcms.utils.callback.IDownloadListener;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class FileUtils {
    private static final String TAG = "FileUtils";
    @SuppressLint("StaticFieldLeak")
    private static Context context;
    private static File audioDir;
    private static File imageDir;
    private static File waterImageDir;
    private static File videoDir;
    private static int index = 1;

    public static void initFileConfig(Context context) {
        FileUtils.context = context;
        File parentDir = new File(context.getFilesDir().getAbsolutePath(), "Casic");
        if (!parentDir.exists()) {
            boolean mkdir = parentDir.mkdir();
            if (mkdir) {
                Log.d(TAG, "initFileConfig: 创建Casic文件夹");
            }
        }
        audioDir = new File(parentDir, "AudioFile");
        if (!audioDir.exists()) {
            boolean mkAudioDir = audioDir.mkdir();
            if (mkAudioDir) {
                Log.d(TAG, "initFileConfig: 创建AudioFile文件夹");
            }
        }
        imageDir = new File(parentDir, "CompressImageFile");
        if (!imageDir.exists()) {
            boolean mkImageDir = imageDir.mkdir();
            if (mkImageDir) {
                Log.d(TAG, "initFileConfig: 创建CompressImageFile文件夹");
            }
        }
        waterImageDir = new File(parentDir, "WaterImageFile");
        if (!waterImageDir.exists()) {
            boolean mkAudioDir = waterImageDir.mkdir();
            if (mkAudioDir) {
                Log.d(TAG, "initFileConfig: 创建WaterImageFile文件夹");
            }
        }
        videoDir = new File(parentDir, "CompressVideoFile");
        if (!videoDir.exists()) {
            boolean mkVideoDir = videoDir.mkdir();
            if (mkVideoDir) {
                Log.d(TAG, "initFileConfig: 创建CompressVideoFile文件夹");
            }
        }
    }

    static File getOutputAudioFile() {
        //如果第一次初始化文件夹未创建成功，那就调用的时候再单独创建一次文件夹
        if (audioDir == null) {
            File parentDir = new File(context.getFilesDir().getAbsolutePath(), "Casic");
            if (!parentDir.exists()) {
                boolean mkdir = parentDir.mkdir();
                if (mkdir) {
                    Log.d(TAG, "getOutputAudioFile: 创建Casic文件夹");
                }
            }
            audioDir = new File(parentDir, "AudioFile");
            if (!audioDir.exists()) {
                boolean mkAudioDir = audioDir.mkdir();
                if (mkAudioDir) {
                    Log.d(TAG, "getOutputAudioFile: 创建AudioFile文件夹");
                }
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        File audioFile = new File(audioDir + File.separator + "AUD_" + timeStamp + ".m4a");
        if (!audioFile.exists()) {
            try {
                audioFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return audioFile;
    }

    public static String getImageCompressPath() {
        if (imageDir == null) {
            File parentDir = new File(context.getFilesDir().getAbsolutePath(), "Casic");
            if (!parentDir.exists()) {
                boolean mkdir = parentDir.mkdir();
                if (mkdir) {
                    Log.d(TAG, "getImageCompressPath: 创建Casic文件夹");
                }
            }
            imageDir = new File(parentDir, "CompressImageFile");
            if (!imageDir.exists()) {
                boolean mkImageDir = imageDir.mkdir();
                if (mkImageDir) {
                    Log.d(TAG, "getImageCompressPath: 创建CompressImageFile文件夹");
                }
            }
        }
        return imageDir.toString();
    }

    static File getWaterImageFile() {
        //如果第一次初始化文件夹未创建成功，那就调用的时候再单独创建一次文件夹
        if (waterImageDir == null) {
            File parentDir = new File(context.getFilesDir().getAbsolutePath(), "Casic");
            if (!parentDir.exists()) {
                boolean mkdir = parentDir.mkdir();
                if (mkdir) {
                    Log.d(TAG, "getWaterImageFile: 创建Casic文件夹");
                }
            }
            waterImageDir = new File(parentDir, "WaterImageFile");
            if (!waterImageDir.exists()) {
                boolean mkAudioDir = waterImageDir.mkdir();
                if (mkAudioDir) {
                    Log.d(TAG, "getWaterImageFile: 创建WaterImageFile文件夹");
                }
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        //index用来区分for循环太快会导致多想图片覆盖压缩问题
        File imageFile = new File(waterImageDir + File.separator + "IMG_" + timeStamp + "_" + (index++) + ".png");
        if (!imageFile.exists()) {
            try {
                imageFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return imageFile;
    }

    //储存下载文件的目录
    private static String getDownloadFilePath() {
        File downloadDir = new File(context.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "");
        if (!downloadDir.exists()) {
            boolean mkdir = downloadDir.mkdir();
            if (mkdir) {
                Log.d(TAG, "getDownloadFilePath: 创建文件夹");
            }
        }
        return downloadDir.toString();
    }

    public static String getOutputVideoFile() {
        if (videoDir == null) {
            File parentDir = new File(context.getFilesDir().getAbsolutePath(), "Casic");
            if (!parentDir.exists()) {
                boolean mkdir = parentDir.mkdir();
                if (mkdir) {
                    Log.d(TAG, "getOutputVideoFile: 创建Casic文件夹");
                }
            }
            videoDir = new File(parentDir, "CompressVideoFile");
            if (!videoDir.exists()) {
                boolean mkVideoDir = videoDir.mkdir();
                if (mkVideoDir) {
                    Log.d(TAG, "getOutputVideoFile: 创建CompressVideoFile文件夹");
                }
            }
        }
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA).format(new Date());
        File videoFile = new File(videoDir + File.separator + "VID_" + timeStamp + ".mp4");
        if (!videoFile.exists()) {
            try {
                videoFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return videoFile.getPath();
    }

    public static void downloadFile(String url, IDownloadListener listener) {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().get().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                String savePath = getDownloadFilePath();
                try {
                    ResponseBody body = response.body();
                    if (body != null) {
                        is = body.byteStream();
                        long total = body.contentLength();
                        listener.onDownloadStart(total);
                        File file = new File(savePath, url.substring(url.lastIndexOf("/") + 1));
                        fos = new FileOutputStream(file);
                        long current = 0;
                        while ((len = is.read(buf)) != -1) {
                            fos.write(buf, 0, len);
                            current += len;
                            listener.onProgressChanged(current);
                        }
                        fos.flush();
                        listener.onDownloadEnd(file);
                    } else {
                        Log.e(TAG, "onResponse: body is null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null)
                            fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
