package com.base.filerecoveryrecyclebin.service;

import android.os.Build;
import android.os.Environment;
import android.os.FileObserver;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.TextUtils;
import android.util.Log;

import com.base.filerecoveryrecyclebin.MyApplication;
import com.base.filerecoveryrecyclebin.activity.recyclebin.RecycleBinFileEx;
import com.base.filerecoveryrecyclebin.help.FileHelp;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FileObserverExample {

    private static final String TAG = "FileObserverExample";
    private HandlerThread fileHandlerThread;
    private Handler fileHandler;

    public static final Set<String> FILE_EXTENSIONS = new HashSet<>(Arrays.asList(
            ".jpg", ".jpeg", ".png", ".gif", ".bmp",
            ".mp4", ".avi", ".mov", ".mkv",
            ".mp3", ".wav", ".aac",
            ".pdf", ".doc", ".docx", ".xls", ".xlsx", ".txt"
    ));

    private FileObserver fileObserver;
    List<File> watchList;

    public void startObserving() {
        // 获取外部存储目录
        List<File> dcimList = FileHelp.INSTANCE.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
        List<File> pictureList = FileHelp.INSTANCE.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
        List<File> downloadList = FileHelp.INSTANCE.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
        List<File> videoList = FileHelp.INSTANCE.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES));
        watchList = new ArrayList();

        watchList.addAll(dcimList);
        watchList.addAll(pictureList);
        watchList.addAll(downloadList);
        watchList.addAll(videoList);
        fileHandlerThread = new HandlerThread("FileObserverThread");
        fileHandlerThread.start();
        fileHandler = new Handler(fileHandlerThread.getLooper());
        fileObserver = new FileObserver(watchList, FileObserver.CREATE | FileObserver.DELETE) {
            @Override
            public void onEvent(int event, String path) {
                Log.d(TAG, "onEvent " + event + "  " + path);
                if (!TextUtils.isEmpty(path)) {
                    Log.d(TAG, "path:  " + path);
                    handleFileEvent(path, event);
                }
            }
        };
        fileObserver.startWatching(); // 启动观察
        Log.d(TAG,"startObserving");
    }

    public void stopObserving() {
        if (fileObserver != null) {
            // 根据 API 版本选择不同的停止方法
            fileObserver.stopWatching();
        }
    }

    // 处理文件事件
    private void handleFileEvent(String path, int event) {
        Log.d(TAG, path);
        // 检查文件扩展名是否在监听范围内
        if (FILE_EXTENSIONS.contains(getFileExtension(path))) {
            if (event == FileObserver.CREATE) {
                Log.d(TAG, "CREATE");
                fileHandler.post(() -> handleFileCreation(path));
            } else if (event == FileObserver.DELETE) {
                Log.d(TAG, "DELETE:" + path);
                BackUpUtils.INSTANCE.deleteFile(path);
            }
        }
    }

    // 获取文件扩展名
    private String getFileExtension(String fileName) {
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return "." + fileName.substring(fileName.lastIndexOf(".") + 1);
        } else {
            return "";
        }
    }

    private void handleFileCreation(String path) {
        // 确保线程安全，这里我们只是打印出来，实际使用中可能需要同步机制
        for (File dir : watchList) {
            File src = new File(dir, path);
            if (src.exists()) {
                Log.d(TAG, "新创建的文件 " + path + " 属于目录: " + dir.getAbsolutePath());
                BackUpUtils.INSTANCE.backupFile(src, path);
                break;
            }
        }
    }


}