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

/**
 * Google Tasks同步服务
 * 负责在后台执行同步操作并提供同步状态通知
 * 通过Intent接收同步命令并通过广播发送同步状态更新
 */
public class GTaskSyncService extends Service {
    // 同步操作类型常量
    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() {
        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() {
        mSyncTask = null;  // 初始化同步任务为null
    }

    /**
     * 处理服务启动命令
     * @param intent 启动意图
     * @param flags 启动标志
     * @param startId 启动ID
     * @return 服务启动模式
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        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();  // 内存不足时取消同步任务
        }
    }

    /**
     * 返回服务绑定接口（此服务不支持绑定）
     * @param intent 绑定意图
     * @return null
     */
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 发送同步状态广播
     * @param msg 同步进度消息
     */
    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);  // 发送广播通知同步状态
    }

    /**
     * 静态方法：从Activity启动同步服务
     * @param activity 调用的Activity
     */
    public static void startSync(Activity activity) {
        GTaskManager.getInstance().setActivityContext(activity);  // 设置Activity上下文
        Intent intent = new Intent(activity, GTaskSyncService.class);
        intent.putExtra(GTaskSyncService.ACTION_STRING_NAME, GTaskSyncService.ACTION_START_SYNC);
        activity.startService(intent);  // 启动同步服务
    }

    /**
     * 静态方法：取消同步
     * @param context 上下文
     */
    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);  // 启动服务并发送取消同步命令
    }

    /**
     * 静态方法：检查是否正在同步
     * @return 是否正在同步
     */
    public static boolean isSyncing() {
        return mSyncTask != null;
    }

    /**
     * 静态方法：获取当前同步进度消息
     * @return 同步进度消息
     */
    public static String getProgressString() {
        return mSyncProgress;
    }
}