
/*
 * 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.gtask.remote;//实现Gtask异步操作过程

import android.app.Notification;//引用的包名
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

import net.micode.notes.R;//引入android自动生成的R类
import net.micode.notes.ui.NotesListActivity;//自动生成的该程序包名下的R.java，专门用于管理二进制资源
import net.micode.notes.ui.NotesPreferenceActivity;


public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {//异步任务类：任务同步和取消，显示同步任务的进程、通知和结果

    private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;//static int变量存储GTask同步通知的ID。

    public interface OnCompleteListener {//初始化异步功能
        void onComplete();
    }

    private Context mContext;//文本内容

    private NotificationManager mNotifiManager;//对象： 通知管理器类的实例化

    private GTaskManager mTaskManager;//实例化任务管理器

    private OnCompleteListener mOnCompleteListener;//实例化是否完成的监听器

    public GTaskASyncTask(Context context, OnCompleteListener listener) {// GTaskASyncTask类的构造函数
        mContext = context;
        mOnCompleteListener = listener;
        mNotifiManager = (NotificationManager) mContext//getSystemService是Activity的一个方法，可根据传入的参数获得应服务的对象。这里以Context的NOTIFICATION_SERVICE为对象。
                .getSystemService(Context.NOTIFICATION_SERVICE);//getSystemService是一种可根据传入的参数获得应服务的对象的端口函数。
        mTaskManager = GTaskManager.getInstance();单例模式创建类的实例
    }

    public void cancelSync() {//取消同步
        mTaskManager.cancelSync();//取消同步
    }

    public void publishProgess(String message) {//显示信息
        publishProgress(new String[] {
            message
        });
    }

    private void showNotification(int tickerId, String content) {//显示通知
        Notification notification = new Notification(R.drawable.notification, mContext//新建通知
                .getString(tickerId), System.currentTimeMillis());
        notification.defaults = Notification.DEFAULT_LIGHTS;
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        PendingIntent pendingIntent;
        if (tickerId != R.string.ticker_success) {//如果同步失败，就从系统取得一个用于启动NotesPreferenceActivity的PendingIntent对象。
            pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
                    NotesPreferenceActivity.class), 0);//如果同步不成功，会从系统获取一个来启动NotesPreferenceActivity的对象

        } else {// 若同步成功，则从系统中获得一个对象来启动NotesListActivity
            pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
                    NotesListActivity.class), 0);
        }
        notification.setLatestEventInfo(mContext, mContext.getString(R.string.app_name), content,//设置最新事件信息
                pendingIntent);
        mNotifiManager.notify(GTASK_SYNC_NOTIFICATION_ID, notification);//通过NotificationManager对象的notify（）方法来执行一个notification的消息
    }

    @Override
    protected Integer doInBackground(Void... unused) {//执行后台操作
        publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
                .getSyncAccountName(mContext)));
        return mTaskManager.sync(mContext, this);//进行后台同步具体操作
    }

    @Override
    protected void onProgressUpdate(String... progress) {//显示进度的更新
        showNotification(R.string.ticker_syncing, progress[0]);
        if (mContext instanceof GTaskSyncService) {//mContext是否在GTaskSyncService类中
            ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
        }
    }

    @Override
    protected void onPostExecute(Integer result) {//设置任务，比如在用户界面显示一个进度条
        if (result == GTaskManager.STATE_SUCCESS) {//同步成功，显示相应的东西。
            showNotification(R.string.ticker_success, mContext.getString(//若同步成功，则显示成功及展示出同步的账户
                    R.string.success_sync_account, mTaskManager.getSyncAccount()));
            NotesPreferenceActivity.setLastSyncTime(mContext, System.currentTimeMillis());//设置当前最新同步时间
        } else if (result == GTaskManager.STATE_NETWORK_ERROR) {//如果网络错误则显示网络错误的通知
            showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_network));
        } else if (result == GTaskManager.STATE_INTERNAL_ERROR) {//网络错误导致同步错误。
            showNotification(R.string.ticker_fail, mContext.getString(R.string.error_sync_internal));
        } else if (result == GTaskManager.STATE_SYNC_CANCELLED) {//如果同步被取消则显示其通知
            showNotification(R.string.ticker_cancel, mContext
                    .getString(R.string.error_sync_cancelled));
        }
        if (mOnCompleteListener != null) {//若监听器为空，则创建新进程
            new Thread(new Runnable() {//创建新进程

                public void run() {
                    mOnCompleteListener.onComplete();//执行完后调用，返回主线程中
                }
            }).start();
        }
    }
}
