package com.hh.lib_device.utils;

import android.os.Environment;
import android.text.TextUtils;
import android.util.Base64;

import com.hh.lib_base.log.AppLogUtils;
import com.hh.lib_base.log.LogType;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;

/**
 * Description: $
 *
 * @author xwh
 * time 2024/11/14
 **/
public class FileSaver {

    private volatile Queue<String> fileQueue = new LinkedList<>();
    private volatile int currentFileIndex = 0;
    private String fileName="";
    private volatile int totalChunk = 0;
    private volatile boolean isRunning= false;
    private volatile SaveThread saveThread;
    private volatile OnSaveFileListener saveFileListener;
    private volatile boolean fileCompleteed =true;

    public FileSaver(String fileName, int totalChunk) {
        this.fileName = fileName;
        this.totalChunk = totalChunk;
        isRunning = true;
    }



    public synchronized void startRead() {
        if (saveThread != null && saveThread.isAlive()) {
            return;
        }
        if (saveThread != null) {
            isRunning = false;
            saveThread.interrupt();
            saveThread = null;
        }
        if (saveThread == null) {
            saveThread = new SaveThread();
        }
        isRunning = true;
        saveThread.start();

    }


    public synchronized void stopRead() {
        if (saveThread == null) {
//            showString("请先启动读卡");
            return;
        }
        isRunning = false;
        saveThread.interrupt();
        saveThread = null;
    }

    private class SaveThread extends Thread {
        public SaveThread() {

        }

        @Override
        public void run() {
            super.run();
            saveNextFile();
        }
    }






    public void addFileToSave(String fileData) {
        synchronized (fileQueue) {
            fileQueue.add(fileData);
           /* if (currentFileIndex == 0) {
                saveNextFile();
            }*/
        }
    }

    private void saveNextFile() {
        synchronized (fileQueue) {
            boolean condition =totalChunk > 0 && currentFileIndex < totalChunk && isRunning;
            while (condition) {
                try {
                    if (fileQueue.isEmpty()) {
                        Thread.sleep(200);
                        continue;
                    }
                    String fileData = fileQueue.poll();
                    if (fileData != null) {
                        // 保存文件的逻辑
                        boolean isSaved= saveFile(fileData);
                        if(!isSaved){
                            fileCompleteed = false;
                        }
                        currentFileIndex++;
                        // 继续保存下一个文件
                        saveNextFile();
                    }
                    if (currentFileIndex == totalChunk) {
                        if(saveFileListener!=null){
                            saveFileListener.onEnd(fileCompleteed,fileCompleteed?"保存成功":"保存失败");
                        }
                        stopRead();
                        return;
                    }

                }catch (InterruptedException e){
                    isRunning =false;
                }

            }
            if (currentFileIndex == totalChunk) {
                if(saveFileListener!=null){
                    saveFileListener.onEnd(fileCompleteed,fileCompleteed?"保存成功":"保存失败");
                }
                stopRead();
            }
        }
    }

    private boolean saveFile(String fileData) {
        if (!createFolder()) {
            AppLogUtils.saveLog(LogType.Logcat, "FileSaver saveFile createFolder Failed ！");
            return false;
        }
        if(TextUtils.isEmpty(fileData)){
            AppLogUtils.saveLog(LogType.Logcat, "FileSaver saveFile content null ！");
            return false;
        }
        // 创建输出文件
        File mp4File = new File(fileName);
        if (!mp4File.exists()) {
            mp4File.mkdir();
        }

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(mp4File);
            byte[] data = Base64.decode(fileData, Base64.DEFAULT);
            fos.write(data);
            return true;
        } catch (Exception e) {
            AppLogUtils.saveLog(LogType.Logcat, "FileSaver saveFile  Failed ！" + e.toString());
            return false;
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {

                }
            }
        }

    }

    private boolean createFolder() {
        File folder = new File(Environment.getExternalStorageDirectory(), "HHArome/video");
        boolean success = false;
        if (!folder.exists()) {
            success = folder.mkdirs(); // 创建文件夹
        }
       return success;
    }


    public void setSaveFileListener(OnSaveFileListener saveFileListener) {
        this.saveFileListener = saveFileListener;
    }

    public interface OnSaveFileListener{
        void onEnd(boolean saved,String msg);
    }
}
