/*
 * 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.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageTool {
    private static final String TAG = "ImageTool";

    // 图片引用标签格式 [图片:filename.jpg]
    private static final String IMAGE_PATTERN = "\\[图片:([^\\]]+)\\]";
    private static final Pattern sImagePattern = Pattern.compile(IMAGE_PATTERN);

    /**
     * 从Uri加载位图
     */
    public static Bitmap getBitmapFromUri(Context context, Uri uri) {
        try {
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            if (inputStream == null) {
                return null;
            }
            
            // 直接解码为位图
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            inputStream.close();
            return bitmap;
        } catch (Exception e) {
            Log.e(TAG, "无法从URI加载图片", e);
            return null;
        }
    }

    /**
     * 保存位图到文件
     */
    public static String saveBitmapToFile(Context context, Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }

        // 生成唯一文件名
        String filename = UUID.randomUUID().toString() + ".jpg";
        File imageFile = new File(ResourceParser.getNotesImageDir(context), filename);
        
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(imageFile);
            // 使用JPEG格式保存，85%质量
            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
            fos.flush();
            return filename;
        } catch (IOException e) {
            Log.e(TAG, "保存图片失败", e);
            return null;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // 忽略
                }
            }
        }
    }

    /**
     * 从文件加载位图
     */
    public static Bitmap loadBitmapFromFile(Context context, String filename) {
        if (TextUtils.isEmpty(filename)) {
            return null;
        }
        
        File imageFile = new File(ResourceParser.getNotesImageDir(context), filename);
        if (!imageFile.exists()) {
            Log.e(TAG, "图片文件不存在: " + imageFile.getAbsolutePath());
            return null;
        }
        
        try {
            // 直接解码文件
            return BitmapFactory.decodeFile(imageFile.getAbsolutePath());
        } catch (Exception e) {
            Log.e(TAG, "加载图片文件失败", e);
            return null;
        }
    }

    /**
     * 处理文本中的图片标记
     */
    public static Spannable processPossibleImagesInText(Context context, String content) {
        if (TextUtils.isEmpty(content)) {
            return new SpannableString("");
        }
        
        SpannableString spannableString = new SpannableString(content);
        Matcher matcher = sImagePattern.matcher(content);
        
        while (matcher.find()) {
            String filename = matcher.group(1);
            if (!TextUtils.isEmpty(filename)) {
                Bitmap bitmap = loadBitmapFromFile(context, filename);
                if (bitmap != null) {
                    ImageSpan imageSpan = new ImageSpan(context, bitmap);
                    spannableString.setSpan(imageSpan, matcher.start(), matcher.end(), 
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    Log.d(TAG, "图片标记处理成功: " + filename);
                }
            }
        }
        
        return spannableString;
    }

    /**
     * 从文本中提取所有图片文件名
     */
    public static String[] extractImagesFromText(String content) {
        if (TextUtils.isEmpty(content)) {
            return new String[0];
        }
        
        java.util.ArrayList<String> images = new java.util.ArrayList<>();
        Matcher matcher = sImagePattern.matcher(content);
        
        while (matcher.find()) {
            String filename = matcher.group(1);
            if (!TextUtils.isEmpty(filename)) {
                images.add(filename);
            }
        }
        
        return images.toArray(new String[0]);
    }
    
    /**
     * 删除与笔记关联的所有图片文件
     */
    public static void deleteImagesForNote(Context context, String content) {
        if (TextUtils.isEmpty(content)) {
            return;
        }
        
        String[] imageFiles = extractImagesFromText(content);
        for (String filename : imageFiles) {
            File imageFile = new File(ResourceParser.getNotesImageDir(context), filename);
            if (imageFile.exists()) {
                imageFile.delete();
            }
        }
    }
} 