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

/*
 *异步操作类，实现Gtask异步操作过程
 *主要方法：
 *private void showNotification(int tickerId, String content) 用于为用户同步当前事件状态
 *protected Integer doInBackground(Void... unused) 后台线程执行，完成任务主要工作
 *protected void onProgressUpdate(String... progress) 主线程运行，以进度条显示用户工作完成状态
 *protected void onPostExecute(Integer result) 更新UI
 */
package net.micode.notes.gtask.remote;

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;
import net.micode.notes.ui.NotesListActivity;
import net.micode.notes.ui.NotesPreferenceActivity;


public class GTaskASyncTask extends AsyncTask<Void, String, Integer> {

    private static int GTASK_SYNC_NOTIFICATION_ID = 5234235;

    public interface OnCompleteListener {
        void onComplete();
    }

    private Context mContext;

    private NotificationManager mNotifiManager;

    private GTaskManager mTaskManager;

    private OnCompleteListener mOnCompleteListener;
    // GTask的一个同步进程类，包含上下文信息，事件完成进度监听方法，通知管理方法，和进程管理方法
    public GTaskASyncTask(Context context, OnCompleteListener listener) {
        mContext = context;
        mOnCompleteListener = listener;
        mNotifiManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        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) {
            pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
                    NotesPreferenceActivity.class), 0);
        // 同步成功显示活动信息列表
        } else {

            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);
    }

    @Override
    protected Integer doInBackground(Void... unused) {
        //利用getString将NotesPreferenceActivity.getSyncAccountName(mContext)的字符串内容
        //传进sync_progress_login中
        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]);
        //判断mContext是否为GTaskSyncService的实例
        if (mContext instanceof GTaskSyncService) {
            ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
        }
    }

    @Override
    //后台运行完后更新ui，显示更新后结果
    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();
        }
    }
}
