/*
 * 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.widget;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.Log;
import android.widget.RemoteViews;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NoteEditActivity;
import net.micode.notes.ui.NotesListActivity;

/**
 * 便签桌面小部件的基类，提供通用功能实现
            部件（如 1x1、4x1 尺寸
            
            bstract class NoteWidgetProvider extends AppWidgetProvider {
    // 查询便签信息的列投影（ID、背景色、摘要内容）
    public static final String [] PROJECTION = new String [] {
        NoteColumns.ID, 
        NoteColumns.BG_COLOR_ID, 
        NoteColumns.SNIPPET 
    };

    // 投影列的索引常量
    public static final int COLUMN_ID           = 0;
    public static final int COLUMN_BG_COLOR_ID  = 1;
    public static final int COLUMN_SNIPPET      = 2;

    // 日志标签
    private static final String TAG = "NoteWidgetProvider";

    /**
     * 当小部件被删除时调用 
     * - 将对应便签的 widget_id 重置为 INVALID_APPWIDGET_ID
     * - 防止数据库中残留无效的小部件关联
     */
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        ContentValues values = new ContentValues();
        values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        for (int i = 0; i < appWidgetIds.length; i++) {
            context.getContentResolver().update(Notes.CONTENT_NOTE_URI,
                    values,
                    NoteColumns.WIDGET_ID + "=?",
                    new String[] { String.valueOf(appWidgetIds[i])});
        }
    }

    /**
     * 查询与小部件关联的便签信息
     * - 过滤条件：widget_id 匹配且便签不在回收站
     * - 返回 Cursor 用于读取便签数据（ID、背景色、摘要）
     */
    private Cursor getNoteWidgetInfo(Context context, int widgetId) {
        return context.getContentResolver().query(Notes.CONTENT_NOTE_URI,
                PROJECTION,
                NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?",
                new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
                null);
    }

    /**
     * 更新小部件内容（简化版，默认非隐私模式）
     */
    protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        update(context, appWidgetManager, appWidgetIds, false);
    }

    /**
     * 更新小部件内容（完整逻辑）
     * - 遍历所有小部件 ID，设置其内容和点击行为
     * - 支持普通模式和隐私模式显示不同内容
     */
    private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds,
            boolean privacyMode) {
        for (int i = 0; i < appWidgetIds.length; i++) {
            if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) {
                // 初始化默认背景色和摘要
                int bgId = ResourceParser.getDefaultBgId(context);
                String snippet = "";
                
                // 创建点击小部件时启动的 Intent
                Intent intent = new Intent(context, NoteEditActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]);
                intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType());

                // 查询关联便签信息
                Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]);
                if (c != null && c.moveToFirst()) {
                    // 检查是否存在多个相同 widget_id 的便签（异常情况）
                    if (c.getCount() > 1) {
                        Log.e(TAG, "Multiple message with same widget id:" + appWidgetIds[i]);
                        c.close();
                        return;
                    }
                    
                    // 读取便签内容
                    snippet = c.getString(COLUMN_SNIPPET);
                    bgId = c.getInt(COLUMN_BG_COLOR_ID);
                    intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID));
                    intent.setAction(Intent.ACTION_VIEW);
                } else {
                    // 无关联便签时显示提示文本
                    snippet = context.getResources().getString(R.string.widget_havenot_content);
                    intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
                }

                // 关闭游标释放资源
                if (c != null) {
                    c.close();
                }

                // 创建并配置小部件视图
                RemoteViews rv = new RemoteViews(context.getPackageName(), getLayoutId());
                rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId));
                intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
                
                /**
                 * 设置小部件点击行为
                 * - 隐私模式：显示提示文本，点击跳转到便签列表
                 * - 普通模式：显示便签内容，点击跳转到编辑界面
                 */
                PendingIntent pendingIntent = null;
                if (privacyMode) {
                    rv.setTextViewText(R.id.widget_text,
                            context.getString(R.string.widget_under_visit_mode));
                    pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], new Intent(
                            context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
                } else {
                    rv.setTextViewText(R.id.widget_text, snippet);
                    pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                }

                // 设置点击事件并更新小部件
                rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent);
                appWidgetManager.updateAppWidget(appWidgetIds[i], rv);
            }
        }
    }

    /**
     * 获取背景资源 ID（子类必须实现）
     * @param bgId 背景色 ID
     * @return 对应的 Drawable 资源 ID
     */
    protected abstract int getBgResourceId(int bgId);

    /**
     * 获取小部件布局 ID（子类必须实现）
     * @return 布局资源 ID（如 R.layout.widget_1x1）
     */
    protected abstract int getLayoutId();

    /**
     * 获取小部件类型（子类必须实现）
     * @return 小部件类型常量（如 Notes.TYPE_WIDGET_1X1）
     */
    protected abstract int getWidgetType();
}