/*
 * 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; //导入widget
import android.app.PendingIntent; //引入各种类
import android.appwidget.AppWidgetManager; //  导入AppWidget
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; //引入android自动生成的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;

public abstract class NoteWidgetProvider extends AppWidgetProvider { //构造了一个类继承Android原有的AppWidgetProvider类
    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"; //定义NoteWidgetProvider为标签TAG
                                                                                              //删除原有的context
    @Override //@Override标识重写，供编译器验证
    public void onDeleted(Context context, int[] appWidgetIds) { //定义函数onDeleted用来进行删除相关操作
        ContentValues values = new ContentValues(); //创建contentvalues对象
        values.put(NoteColumns.WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID); //将当前NoteColumns类的ID存入数据库中
        for (int i = 0; i < appWidgetIds.length; i++) {
            context.getContentResolver().update(Notes.CONTENT_NOTE_URI, //遍历并修改所有的URI值
                    values,
                    NoteColumns.WIDGET_ID + "=?",
                    new String[] { String.valueOf(appWidgetIds[i])}); //valueOf() 方法用于返回给定参数的原生 Number 对象值
        }
    }

    private Cursor getNoteWidgetInfo(Context context, int widgetId) { //获取窗口宽度信息
        return context.getContentResolver().query(Notes.CONTENT_NOTE_URI, //定义context寻找并返回获取的widget窗口信息
                PROJECTION,
                NoteColumns.WIDGET_ID + "=? AND " + NoteColumns.PARENT_ID + "<>?", //用ID来筛选，同时要是存在于未被删除的文件夹中
                new String[] { String.valueOf(widgetId), String.valueOf(Notes.ID_TRASH_FOLER) },
                null);
    }
                                                                                                                                      //更新挂件信息
    protected void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { //用updata函数来实现小米便签挂件appWidgetlds信息的返回与更新
        update(context, appWidgetManager, appWidgetIds, false); //更新窗口部件
    }

    private void update(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds, //把更新的窗口ID保存到窗口管理器中
            boolean privacyMode) {
        for (int i = 0; i < appWidgetIds.length; i++) { //每添加一个widget就会进行一次循环更新操作
            if (appWidgetIds[i] != AppWidgetManager.INVALID_APPWIDGET_ID) { //若ID对应的窗口已经关闭，则跳过
                int bgId = ResourceParser.getDefaultBgId(context); //跳过那些已经关闭的窗口的ID
                String snippet = "";
                Intent intent = new Intent(context, NoteEditActivity.class); //创建intent对象
                intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); //若目标在栈顶则跳转，否则新建
                intent.putExtra(Notes.INTENT_EXTRA_WIDGET_ID, appWidgetIds[i]); //通过使用Intent对象（用于Activity之间传递参数）来更新小米便签挂件的ID和类型的相关信息。
                intent.putExtra(Notes.INTENT_EXTRA_WIDGET_TYPE, getWidgetType()); //附加组件类型

                Cursor c = getNoteWidgetInfo(context, appWidgetIds[i]); //获取特定的对应对象
                if (c != null && c.moveToFirst()) { //处理多个窗口同位出现的情况
                    if (c.getCount() > 1) { //cursor.getCount()返回cursor中的行数
                        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); //获取ID值
                    intent.putExtra(Intent.EXTRA_UID, c.getLong(COLUMN_ID)); //目的
                    intent.setAction(Intent.ACTION_VIEW); //为Intent设置一个动作Action
                } else { //在Intent内设置一个Action
                    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()); //获取AppWidget对应的视图
                rv.setImageViewResource(R.id.widget_bg_image, getBgResourceId(bgId)); //根据当前的属性，设置背景图片
                intent.putExtra(Notes.INTENT_EXTRA_BACKGROUND_ID, bgId);
                /**
                 * Generate the pending intent to start host for the widget
                 */                                                                                          //为小部件生成启动主机的挂起意图
                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( //获得一个PendingIntent，如果该意图要发生就相当于Context.startActivity(Intent)
                            context, NotesListActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
                } else {
                    rv.setTextViewText(R.id.widget_text, snippet); //设置 点击“按钮(widget_text)”时会触发的Intent，从而对按钮点击事件进行处理
                    pendingIntent = PendingIntent.getActivity(context, appWidgetIds[i], intent,
                            PendingIntent.FLAG_UPDATE_CURRENT);
                }

                rv.setOnClickPendingIntent(R.id.widget_text, pendingIntent); //窗口服务部件
                appWidgetManager.updateAppWidget(appWidgetIds[i], rv); //调用集合管理器对集合进行更新
            } //其中public void updateAppWidget(int appWidgetIds, RemoteViews views)功能：以特定的views视图更新所有appWidgetIds的窗口小部件(AppWidget) 。同时会发送ACTION_APPWIDGET_UPDATE广播
        }
    }

    protected abstract int getBgResourceId(int bgId); //从背景资源中获取当前应用ID
 
    protected abstract int getLayoutId(); //获取布局ID

    protected abstract int getWidgetType(); //获取挂件的类型，即2x2型或者4x4型
} 
