/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.tool;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.util.Log;

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

/**
 * 背景管理器类
 * 负责背景图片的选择、存储和应用
 */
public class BackgroundManager {
    private static final String TAG = "BackgroundManager";
    private static final String BACKGROUND_DIR = "note_backgrounds";
    private static final String IMAGE_DIR = "note_images";
    private Context mContext;

    /**
     * 构造方法
     * @param context 上下文对象
     */
    public BackgroundManager(Context context) {
        mContext = context;
        // 初始化目录
        initDirectories();
    }

    /**
     * 初始化目录
     */
    private void initDirectories() {
        // 创建背景图片目录
        File backgroundDir = getBackgroundDir();
        if (!backgroundDir.exists()) {
            if (!backgroundDir.mkdirs()) {
                Log.e(TAG, "Failed to create background directory");
            }
        }

        // 创建插入图片目录
        File imageDir = getImageDir();
        if (!imageDir.exists()) {
            if (!imageDir.mkdirs()) {
                Log.e(TAG, "Failed to create image directory");
            }
        }
    }

    /**
     * 获取背景图片目录
     * @return 背景图片目录
     */
    public File getBackgroundDir() {
        return new File(mContext.getFilesDir(), BACKGROUND_DIR);
    }

    /**
     * 获取插入图片目录
     * @return 插入图片目录
     */
    public File getImageDir() {
        return new File(mContext.getFilesDir(), IMAGE_DIR);
    }

    /**
     * 保存背景图片并返回路径
     * @param sourceUri 源图片URI
     * @return 保存后的图片路径
     */
    public String saveBackgroundImage(Uri sourceUri) {
        try {
            // 创建目标文件
            String fileName = generateUniqueFileName();
            File destFile = new File(getBackgroundDir(), fileName);

            // 复制文件
            copyFile(sourceUri, destFile);

            // 返回文件路径
            return destFile.getAbsolutePath();
        } catch (IOException e) {
            Log.e(TAG, "Error saving background image: " + e.getMessage());
            return null;
        }
    }

    /**
     * 保存插入的图片并返回路径
     * @param sourceUri 源图片URI
     * @return 保存后的图片路径
     */
    public String saveInsertedImage(Uri sourceUri) {
        try {
            // 创建目标文件
            String fileName = generateUniqueFileName();
            File destFile = new File(getImageDir(), fileName);

            // 复制文件
            copyFile(sourceUri, destFile);

            // 返回文件路径
            return destFile.getAbsolutePath();
        } catch (IOException e) {
            Log.e(TAG, "Error saving inserted image: " + e.getMessage());
            return null;
        }
    }

    /**
     * 复制文件
     * @param sourceUri 源文件URI
     * @param destFile 目标文件
     * @throws IOException IO异常
     */
    private void copyFile(Uri sourceUri, File destFile) throws IOException {
        InputStream is = null;
        OutputStream os = null;
        try {
            is = mContext.getContentResolver().openInputStream(sourceUri);
            os = new FileOutputStream(destFile);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
        } finally {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
        }
    }

    /**
     * 生成唯一文件名
     * @return 唯一文件名
     */
    private String generateUniqueFileName() {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        return "IMG_" + timeStamp + ".jpg";
    }

    /**
     * 根据路径加载背景图片
     * @param path 图片路径
     * @return 背景图片的Drawable对象
     */
    public Drawable loadBackground(String path) {
        if (path == null || path.isEmpty()) {
            return null;
        }

        try {
            File file = new File(path);
            if (!file.exists()) {
                Log.e(TAG, "Background image file not found: " + path);
                return null;
            }

            Bitmap bitmap = BitmapFactory.decodeFile(path);
            if (bitmap == null) {
                Log.e(TAG, "Failed to decode background image: " + path);
                return null;
            }

            return new BitmapDrawable(mContext.getResources(), bitmap);
        } catch (Exception e) {
            Log.e(TAG, "Error loading background: " + e.getMessage());
            return null;
        }
    }

    /**
     * 清理背景图片文件
     * @param path 图片路径
     * @return 是否清理成功
     */
    public boolean cleanupBackgroundImage(String path) {
        if (path == null || path.isEmpty()) {
            return false;
        }

        File file = new File(path);
        if (file.exists()) {
            if (file.delete()) {
                Log.d(TAG, "Background image deleted: " + path);
                return true;
            } else {
                Log.e(TAG, "Failed to delete background image: " + path);
                return false;
            }
        }
        return false;
    }

    /**
     * 清理插入的图片文件
     * @param path 图片路径
     * @return 是否清理成功
     */
    public boolean cleanupInsertedImage(String path) {
        if (path == null || path.isEmpty()) {
            return false;
        }

        File file = new File(path);
        if (file.exists()) {
            if (file.delete()) {
                Log.d(TAG, "Inserted image deleted: " + path);
                return true;
            } else {
                Log.e(TAG, "Failed to delete inserted image: " + path);
                return false;
            }
        }
        return false;
    }

    /**
     * 检查图片文件是否存在
     * @param path 图片路径
     * @return 是否存在
     */
    public boolean isImageExists(String path) {
        if (path == null || path.isEmpty()) {
            return false;
        }
        File file = new File(path);
        return file.exists() && file.isFile();
    }
}
