package cc.winboll.studio.powerbell.utils;

import android.content.Context;
import cc.winboll.studio.powerbell.model.BackgroundBean;
import java.io.File;
import java.util.UUID;
import cc.winboll.studio.libappbase.ToastUtils;

/**
 * @Author ZhanGSKen<zhangsken@qq.com>
 * @Date 2024/07/18 12:07:20
 * @Describe 背景图片工具集（修复单例模式，线程安全）
 */
public class BackgroundSourceUtils {

    public static final String TAG = "BackgroundPictureUtils";

    // 1. 静态实例加volatile，禁止指令重排，保证可见性
    private static volatile BackgroundSourceUtils sInstance;
    private Context mContext;
	private File currentBackgroundBeanFile;
    private BackgroundBean currentBackgroundBean;
	private File previewBackgroundBeanFile;
    private BackgroundBean previewBackgroundBean;
	// 应用外部存储文件夹路径
	private File fUtilsDir;
	private File fModelDir;
    // 背景图片目录
    private File fBackgroundSourceDir;

    // 2. 私有构造器（加防反射逻辑）
    private BackgroundSourceUtils(Context context) {
        // 防反射破坏：若已有实例，抛异常阻止创建
        if (sInstance != null) {
            throw new RuntimeException("BackgroundSourceUtils 是单例类，禁止重复创建！");
        }
        // 上下文建议用Application Context，避免内存泄漏
        this.mContext = context.getApplicationContext();
        fUtilsDir = this.mContext.getExternalFilesDir(TAG);
		fModelDir = new File(fUtilsDir, "ModelDir");
		currentBackgroundBeanFile = new File(fModelDir, "currentBackgroundBean.json");
		previewBackgroundBeanFile = new File(fModelDir, "previewBackgroundBean.json");
        fBackgroundSourceDir = new File(fUtilsDir, "BackgroundSource");
		
		// 加载配置
        loadSettings();
    }

    // 3. 双重校验锁单例（线程安全，高效）
    public static BackgroundSourceUtils getInstance(Context context) {
        // 第一重校验：避免每次调用都加锁（提高效率）
        if (sInstance == null) {
            // 同步锁：保证同一时刻只有一个线程进入创建逻辑
            synchronized (BackgroundSourceUtils.class) {
                // 第二重校验：防止多线程并发时重复创建（核心）
                if (sInstance == null) {
                    sInstance = new BackgroundSourceUtils(context);
                }
            }
        }
        return sInstance;
    }

    /*
	 * 加载背景图片配置数据
	 */
    void loadSettings() {
        currentBackgroundBean = BackgroundBean.loadBeanFromFile(currentBackgroundBeanFile.getAbsolutePath(), BackgroundBean.class);
        if (currentBackgroundBean == null) {
            currentBackgroundBean = new BackgroundBean();
            BackgroundBean.saveBeanToFile(currentBackgroundBeanFile.getAbsolutePath(), currentBackgroundBean);
        }
		previewBackgroundBean = BackgroundBean.loadBeanFromFile(previewBackgroundBeanFile.getAbsolutePath(), BackgroundBean.class);
        if (previewBackgroundBean == null) {
            previewBackgroundBean = new BackgroundBean();
            BackgroundBean.saveBeanToFile(previewBackgroundBeanFile.getAbsolutePath(), previewBackgroundBean);
        }
    }
	
	public BackgroundBean getCurrentBackgroundBean() {
		return currentBackgroundBean;
	}
	
	public BackgroundBean getPreviewBackgroundBean() {
		return previewBackgroundBean;
	}

    public String getCurrentBackgroundFilePath() {
		loadSettings();
		File file = new File(fBackgroundSourceDir, currentBackgroundBean.getBackgroundFileName());
		return file.getAbsolutePath();
	}

    public String getPreviewBackgroundFilePath() {
		loadSettings();
		File file = new File(fBackgroundSourceDir, previewBackgroundBean.getBackgroundFileName());
		return file.getAbsolutePath();
	}
	
	public String getPreviewBackgroundScaledCompressFilePath() {
		loadSettings();
		File file = new File(fBackgroundSourceDir, previewBackgroundBean.getBackgroundScaledCompressFileName());
		return file.getAbsolutePath();
	}

	public void saveSettings() {
        BackgroundBean.saveBeanToFile(currentBackgroundBeanFile.getAbsolutePath(), currentBackgroundBean);
		BackgroundBean.saveBeanToFile(previewBackgroundBeanFile.getAbsolutePath(), previewBackgroundBean);
    }
	
    public String getBackgroundSourceDirPath() {
        return fBackgroundSourceDir.getAbsolutePath();
    }
	
	/*
	 * 保存图片到预览模型, 并返回预览模型数据
	 */
	public BackgroundBean saveFileToPreviewBean(File sourceFile, String fileInfo) {
		File previewBackgroundFile = new File(fBackgroundSourceDir, FileUtils.createUniqueFileName(sourceFile));
		//ToastUtils.show(String.format("saveFileToPreviewBean previewBackgroundFile : %s", previewBackgroundFile.getAbsolutePath()));
		
		FileUtils.copyFile(sourceFile, previewBackgroundFile);
		previewBackgroundBean = new BackgroundBean();
		previewBackgroundBean.setBackgroundFileName(previewBackgroundFile.getName());
		previewBackgroundBean.setBackgroundScaledCompressFileName("ScaledCompress_"+previewBackgroundFile.getName());
		previewBackgroundBean.setBackgroundFileName(fileInfo);
		saveSettings();
		
		ToastUtils.show(String.format("saveFileToPreviewBean getPreviewBackgroundFilePath() : %s", getPreviewBackgroundFilePath()));
		
		return previewBackgroundBean;
	}
	
	public void commitPreviewSourceToCurrent() {
		currentBackgroundBean = previewBackgroundBean;
		saveSettings();
	}
	
	public void setCurrentSourceToPreview() {
		previewBackgroundBean = currentBackgroundBean;
		saveSettings();
	}
}

