package com.base.filerecoveryrecyclebin.service;

import static android.os.FileObserver.ALL_EVENTS;
import static android.os.FileObserver.ATTRIB;
import static android.os.FileObserver.MOVED_FROM;

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));
        List<File> musicList = FileHelp.INSTANCE.getFileFolder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC));
        watchList = new ArrayList();

        watchList.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM));
        watchList.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
        watchList.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
        watchList.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES));
        watchList.add(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC));
        watchList.addAll(dcimList);
        watchList.addAll(pictureList);
        watchList.addAll(downloadList);
        watchList.addAll(videoList);
        watchList.addAll(musicList);
        fileHandlerThread = new HandlerThread("FileObserverThread");
        fileHandlerThread.start();
        fileHandler = new Handler(fileHandlerThread.getLooper());
        fileObserver = new FileObserver(watchList, FileObserver.CREATE | FileObserver.DELETE | FileObserver.DELETE_SELF | FileObserver.MOVED_FROM | FileObserver.MOVED_TO | FileObserver.MODIFY) {
            @Override
            public void onEvent(int event, String path) {
                Log.e(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, event + "    " + FileObserver.DELETE_SELF + "   " + path);
        // 检查文件扩展名是否在监听范围内
        if (FILE_EXTENSIONS.contains(getFileExtension(path))) {
            if (event == FileObserver.CREATE || event == FileObserver.MOVED_TO || event == FileObserver.MODIFY) {
                Log.d(TAG, "CREATE");
                fileHandler.removeCallbacksAndMessages(null);
                fileHandler.postDelayed(() -> handleFileCreation(path), 2000);
            } else if (event == FileObserver.DELETE || event == FileObserver.DELETE_SELF || event == FileObserver.MOVED_FROM) {
                Log.d(TAG, event + " 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;
            }
        }
    }


}