/*
 * 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.Activity;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;

public class GTaskSyncService extends Service {
    /*
    跟”同步“（包名称）功能对应的类GTaskSyncService的定义
    下面定义的静态常量分别表示动作类型的字符串名称、开始同步的动作类型、取消同步的动作类型、无效的动作类型、GTask服务的广播名称、GTask服务的广播是否正在同步、GTask服务的广播进度消息
     还有两个静态变量mSyncTask和mSyncProgress，在最后两个，分别表示同步任务和同步进度

     */
    public final static String ACTION_STRING_NAME = "sync_action_type";

    public final static int ACTION_START_SYNC = 0;

    public final static int ACTION_CANCEL_SYNC = 1;

    public final static int ACTION_INVALID = 2;

    public final static String GTASK_SERVICE_BROADCAST_NAME = "net.micode.notes.gtask.remote.gtask_sync_service";

    public final static String GTASK_SERVICE_BROADCAST_IS_SYNCING = "isSyncing";

    public final static String GTASK_SERVICE_BROADCAST_PROGRESS_MSG = "progressMsg";

    private static GTaskASyncTask mSyncTask = null;

    private static String mSyncProgress = "";

    private void startSync() {//用于开始同步任务，如果当前没有同步任务，则创建一个新的GTaskASyncTask实例，并在同步完成后发送广播并停止Service
        if (mSyncTask == null) {
            mSyncTask = new GTaskASyncTask(this, new GTaskASyncTask.OnCompleteListener() {
                public void onComplete() {
                    mSyncTask = null;
                    sendBroadcast("");
                    stopSelf();
                }
            });
            sendBroadcast("");
            mSyncTask.execute();
        }
    }

    private void cancelSync() {//用于取消同步任务，如果当前有同步任务，则取消同步
        if (mSyncTask != null) {
            mSyncTask.cancelSync();
        }
    }

    @Override
    public void onCreate() {//在Service创建时将mSyncTask置为null
        mSyncTask = null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {//在接收到指定动作类型的Intent时执行相应的操作，包括开始同步和取消同步
        Bundle bundle = intent.getExtras();
        if (bundle != null && bundle.containsKey(ACTION_STRING_NAME)) {
            switch (bundle.getInt(ACTION_STRING_NAME, ACTION_INVALID)) {
                case ACTION_START_SYNC:
                    startSync();
                    break;
                case ACTION_CANCEL_SYNC:
                    cancelSync();
                    break;
                default:
                    break;
            }
            return START_STICKY;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onLowMemory() {//方法在系统内存不足时取消同步任务
        if (mSyncTask != null) {
            mSyncTask.cancelSync();
        }
    }

    public IBinder onBind(Intent intent) {
        return null;
    }

    public void sendBroadcast(String msg) {//用于发送广播，其中包括同步任务是否正在进行和同步进度消息
        mSyncProgress = msg;
        Intent intent = new Intent(GTASK_SERVICE_BROADCAST_NAME);
        intent.putExtra(GTASK_SERVICE_BROADCAST_IS_SYNCING, mSyncTask != null);
        intent.putExtra(GTASK_SERVICE_BROADCAST_PROGRESS_MSG, msg);
        sendBroadcast(intent);
    }

    //startSync()和cancelSync()方法分别用于在Activity和Context中开始和取消同步任务
    public static void startSync(Activity activity) {
        GTaskManager.getInstance().setActivityContext(activity);
        Intent intent = new Intent(activity, GTaskSyncService.class);
        intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
        activity.startService(intent);
    }

    public static void cancelSync(Context context) {
        Intent intent = new Intent(context, GTaskSyncService.class);
        intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_CANCEL_SYNC);
        context.startService(intent);
    }

    public static boolean isSyncing() {//用于判断是否有同步任务正在进行
        return mSyncTask != null;
    }

    public static String getProgressString() {//用于获取同步进度消息
        return mSyncProgress;
    }
}
