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

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;

/*
 *  GTaskASyncTask����һ���첽�����࣬����ִ��Google�����ͬ��������
 * ����̳���AsyncTask�����ں�̨�߳���ִ��ͬ��������ͬʱ��UI�߳��и��½��Ⱥͽ����
 */
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;
/*
 * ���캯������ʼ�������ġ�֪ͨ���������������������ɼ�������
 * @param context  ������
 * @param listener ��ɼ�����
 */
    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
        });
    }
/*
 * ��ʾ֪ͨ��
 * @param tickerId ֪ͨ����ʾ�ı�ID
 * @param content  ֪ͨ������
 */
    private void showNotification(int tickerId, String content) {
    	// ����һ���µ�Notification����
        Notification notification = new Notification(R.drawable.notification, mContext
                .getString(tickerId), System.currentTimeMillis());
        // ����֪ͨ��Ĭ�ϵƹ�Ч��
        notification.defaults = Notification.DEFAULT_LIGHTS;
        // ����֪ͨ�ı�־���Զ�ȡ��֪ͨ
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        // ����PendingIntent���������û����֪ͨʱ������Ӧ��Activity
        PendingIntent pendingIntent;
        if (tickerId != R.string.ticker_success) {
        	 // ���֪ͨ���dzɹ�֪ͨ������NotesPreferenceActivity
            pendingIntent = PendingIntent.getActivity(mContext, 0, new Intent(mContext,
                    NotesPreferenceActivity.class), 0);

        } else {
        	 // ���֪ͨ�dzɹ�֪ͨ������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);
    }
/*
 * �ں�̨�߳���ִ��ͬ��������
 * @param unused δʹ�õIJ���
 * @return ͬ�����״̬��
 */
    @Override
    protected Integer doInBackground(Void... unused) {
    	// ������¼������Ϣ
        publishProgess(mContext.getString(R.string.sync_progress_login, NotesPreferenceActivity
                .getSyncAccountName(mContext)));
        // ���������������ͬ��������������ͬ�����״̬��
        return mTaskManager.sync(mContext, this);
    }
/*
 * ��UI�߳��и��½��ȡ�
 * @param progress ������Ϣ
 */
    @Override
    protected void onProgressUpdate(String... progress) {
    	// ��ʾͬ������֪ͨ
        showNotification(R.string.ticker_syncing, progress[0]);
        // �����������GTaskSyncService��ʵ�������͹㲥
        if (mContext instanceof GTaskSyncService) {
            ((GTaskSyncService) mContext).sendBroadcast(progress[0]);
        }
    }
/*
 * ��UI�߳��д���ͬ�������
 * @param result ͬ�����״̬��
 */
    @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));
        }
        // ���������ɼ��������������̵߳���onComplete����
        if (mOnCompleteListener != null) {
            new Thread(new Runnable() {

                public void run() {
                    mOnCompleteListener.onComplete();
                }
            }).start();
        }
    }
}