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

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceCategory;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.gtask.remote.GTaskSyncService;

/**
 * 笔记设置页面。
 * <p>职责：承载账户绑定/切换、GTask 同步开关、上次同步时间展示、背景随机开关等设置。</p>
 * <p>关键点：绑定账户时需清理本地 gtask 关联字段；同步过程中禁止修改账户；页面通过广播实时刷新同步状态。</p>
 */
/**
 * 设置活动，用于管理同步账户、最后同步时间和背景颜色偏好
 */
public class NotesPreferenceActivity extends PreferenceActivity {
    /** 偏好设置文件名 */
    public static final String PREFERENCE_NAME = "notes_preferences";

    /** 同步账户名存储键 */
    public static final String PREFERENCE_SYNC_ACCOUNT_NAME = "pref_key_account_name";

    /** 最后同步时间存储键 */
    public static final String PREFERENCE_LAST_SYNC_TIME = "pref_last_sync_time";

    /** 设置背景颜色的偏好键 */
    public static final String PREFERENCE_SET_BG_COLOR_KEY = "pref_key_bg_random_appear";

    /** 同步账户的偏好键 */
    private static final String PREFERENCE_SYNC_ACCOUNT_KEY = "pref_sync_account_key";

    /** 账户权限过滤键 */
    private static final String AUTHORITIES_FILTER_KEY = "authorities";

    /** 账户偏好分类 */
    private PreferenceCategory mAccountCategory;

    /** 同步状态广播接收器 */
    private GTaskReceiver mReceiver;

    /** 原始账户列表 */
    private Account[] mOriAccounts;

    /** 是否添加了新账户 */
    private boolean mHasAddedAccount;

    /**
     * 创建活动时调用，初始化布局、偏好设置和广播接收器
     * @param icicle 保存的实例状态
     */
    @Override
    protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        /* 使用应用图标作为导航 */
        getActionBar().setDisplayHomeAsUpEnabled(true);

        // 从资源文件加载偏好设置
        addPreferencesFromResource(R.xml.preferences);
        // 获取账户偏好分类
        mAccountCategory = (PreferenceCategory) findPreference(PREFERENCE_SYNC_ACCOUNT_KEY);
        // 创建并注册同步状态广播接收器
        mReceiver = new GTaskReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(GTaskSyncService.GTASK_SERVICE_BROADCAST_NAME);
        registerReceiver(mReceiver, filter);

        mOriAccounts = null;
        // 加载设置头部布局
        View header = LayoutInflater.from(this).inflate(R.layout.settings_header, null);
        getListView().addHeaderView(header, null, true);
    }

    /**
     * 活动恢复时调用，检查是否添加了新账户并刷新UI
     */
    @Override
    protected void onResume() {
        super.onResume();

        // 若用户刚新增了 Google 账号，自动选中新账号为同步账号
        if (mHasAddedAccount) {
            Account[] accounts = getGoogleAccounts();
            if (mOriAccounts != null && accounts.length > mOriAccounts.length) {
                // 查找新增的账户
                for (Account accountNew : accounts) {
                    boolean found = false;
                    for (Account accountOld : mOriAccounts) {
                        if (TextUtils.equals(accountOld.name, accountNew.name)) {
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        // 设置新增账户为同步账户
                        setSyncAccount(accountNew.name);
                        break;
                    }
                }
            }
        }

        // 刷新UI界面
        refreshUI();
    }

    /**
     * 活动销毁时调用，取消注册广播接收器
     */
    @Override
    protected void onDestroy() {
        // 取消注册同步状态广播接收器
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
        super.onDestroy();
    }

    /**
     * 加载账户偏好设置，创建账户选择偏好项
     */
    private void loadAccountPreference() {
        // 清空账户偏好分类中的所有项
        mAccountCategory.removeAll();

        // 创建账户选择偏好项
        Preference accountPref = new Preference(this);
        final String defaultAccount = getSyncAccountName(this);
        accountPref.setTitle(getString(R.string.preferences_account_title));
        accountPref.setSummary(getString(R.string.preferences_account_summary));
        // 设置偏好项点击监听器
        accountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
            public boolean onPreferenceClick(Preference preference) {
                // 只有当不同步时才能更改账户
                if (!GTaskSyncService.isSyncing()) {
                    if (TextUtils.isEmpty(defaultAccount)) {
                        // 首次设置账户，显示账户选择对话框
                        showSelectAccountAlertDialog();
                    } else {
                        // 已绑定过账号，提示更换风险
                        showChangeAccountConfirmAlertDialog();
                    }
                } else {
                    // 同步中不能更改账户，显示提示信息
                    Toast.makeText(NotesPreferenceActivity.this,
                            R.string.preferences_toast_cannot_change_account, Toast.LENGTH_SHORT)
                            .show();
                }
                return true;
            }
        });

        // 将账户偏好项添加到分类中
        mAccountCategory.addPreference(accountPref);
    }

    /**
     * 加载同步按钮和最后同步时间显示
     */
    private void loadSyncButton() {
        // 获取同步按钮和最后同步时间文本视图
        Button syncButton = (Button) findViewById(R.id.preference_sync_button);
        TextView lastSyncTimeView = (TextView) findViewById(R.id.prefenerece_sync_status_textview);

        // 根据同步状态配置按钮文案与行为
        if (GTaskSyncService.isSyncing()) {
            // 同步中，按钮显示取消同步
            syncButton.setText(getString(R.string.preferences_button_sync_cancel));
            syncButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // 取消同步
                    GTaskSyncService.cancelSync(NotesPreferenceActivity.this);
                }
            });
        } else {
            // 未同步，按钮显示立即同步
            syncButton.setText(getString(R.string.preferences_button_sync_immediately));
            syncButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    // 开始同步
                    GTaskSyncService.startSync(NotesPreferenceActivity.this);
                }
            });
        }
        // 只有设置了同步账户，按钮才可用
        syncButton.setEnabled(!TextUtils.isEmpty(getSyncAccountName(this)));

        // 展示最近同步时间或实时进度
        if (GTaskSyncService.isSyncing()) {
            // 同步中，显示同步进度
            lastSyncTimeView.setText(GTaskSyncService.getProgressString());
            lastSyncTimeView.setVisibility(View.VISIBLE);
        } else {
            // 未同步，显示最后同步时间
            long lastSyncTime = getLastSyncTime(this);
            if (lastSyncTime != 0) {
                // 格式化并显示最后同步时间
                lastSyncTimeView.setText(getString(R.string.preferences_last_sync_time,
                        DateFormat.format(getString(R.string.preferences_last_sync_time_format),
                                lastSyncTime)));
                lastSyncTimeView.setVisibility(View.VISIBLE);
            } else {
                // 从未同步过，隐藏时间显示
                lastSyncTimeView.setVisibility(View.GONE);
            }
        }
    }

    /**
     * 刷新UI界面，重新加载账户偏好和同步按钮
     */
    private void refreshUI() {
        loadAccountPreference();
        loadSyncButton();
    }

    /**
     * 显示选择账户的对话框，允许用户选择已有账户或添加新账户
     */
    private void showSelectAccountAlertDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        // 加载自定义标题视图
        View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
        TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
        titleTextView.setText(getString(R.string.preferences_dialog_select_account_title));
        TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
        subtitleTextView.setText(getString(R.string.preferences_dialog_select_account_tips));

        // 设置对话框标题和空的确定按钮
        dialogBuilder.setCustomTitle(titleView);
        dialogBuilder.setPositiveButton(null, null);

        // 获取所有Google账户
        Account[] accounts = getGoogleAccounts();
        String defAccount = getSyncAccountName(this);

        // 保存原始账户列表和添加账户标志
        mOriAccounts = accounts;
        mHasAddedAccount = false;

        if (accounts.length > 0) {
            // 创建账户列表项
            CharSequence[] items = new CharSequence[accounts.length];
            final CharSequence[] itemMapping = items;
            int checkedItem = -1;
            int index = 0;
            for (Account account : accounts) {
                // 标记当前默认账户
                if (TextUtils.equals(account.name, defAccount)) {
                    checkedItem = index;
                }
                items[index++] = account.name;
            }
            // 设置单选列表项和选择监听器
            dialogBuilder.setSingleChoiceItems(items, checkedItem,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            // 设置选择的账户为同步账户
                            setSyncAccount(itemMapping[which].toString());
                            dialog.dismiss();
                            refreshUI();
                        }
                    });
        }

        // 加载添加账户视图
        View addAccountView = LayoutInflater.from(this).inflate(R.layout.add_account_text, null);
        dialogBuilder.setView(addAccountView);

        // 显示对话框并设置添加账户点击监听器
        final AlertDialog dialog = dialogBuilder.show();
        addAccountView.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 标记已添加账户
                mHasAddedAccount = true;
                // 打开添加账户设置界面
                Intent intent = new Intent("android.settings.ADD_ACCOUNT_SETTINGS");
                intent.putExtra(AUTHORITIES_FILTER_KEY, new String[] {
                    "gmail-ls"
                });
                startActivityForResult(intent, -1);
                dialog.dismiss();
            }
        });
    }

    /**
     * 显示更改账户的确认对话框，提醒用户更改账户的风险
     */
    private void showChangeAccountConfirmAlertDialog() {
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

        // 加载自定义标题视图
        View titleView = LayoutInflater.from(this).inflate(R.layout.account_dialog_title, null);
        TextView titleTextView = (TextView) titleView.findViewById(R.id.account_dialog_title);
        titleTextView.setText(getString(R.string.preferences_dialog_change_account_title,
                getSyncAccountName(this)));
        TextView subtitleTextView = (TextView) titleView.findViewById(R.id.account_dialog_subtitle);
        subtitleTextView.setText(getString(R.string.preferences_dialog_change_account_warn_msg));
        dialogBuilder.setCustomTitle(titleView);

        // 创建菜单项数组
        CharSequence[] menuItemArray = new CharSequence[] {
                getString(R.string.preferences_menu_change_account),
                getString(R.string.preferences_menu_remove_account),
                getString(R.string.preferences_menu_cancel)
        };
        // 设置菜单项点击监听器
        dialogBuilder.setItems(menuItemArray, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    // 更改账户，显示账户选择对话框
                    showSelectAccountAlertDialog();
                } else if (which == 1) {
                    // 移除账户
                    removeSyncAccount();
                    refreshUI();
                }
            }
        });
        // 显示对话框
        dialogBuilder.show();
    }

    /**
     * 获取设备上所有的Google账户
     * @return Google账户数组
     */
    private Account[] getGoogleAccounts() {
        AccountManager accountManager = AccountManager.get(this);
        return accountManager.getAccountsByType("com.google");
    }

    /**
     * 设置同步账户，并清理相关的本地同步信息
     * @param account 要设置的账户名
     */
    private void setSyncAccount(String account) {
        // 只有当账户名不同时才更新
        if (!getSyncAccountName(this).equals(account)) {
            // 更新账户偏好设置
            SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();
            if (account != null) {
                editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, account);
            } else {
                editor.putString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
            }
            editor.commit();

            // 清除最后同步时间
            setLastSyncTime(this, 0);

            // 在后台线程中清除本地Google Tasks相关信息
            new Thread(new Runnable() {
                public void run() {
                    ContentValues values = new ContentValues();
                    values.put(NoteColumns.GTASK_ID, "");
                    values.put(NoteColumns.SYNC_ID, 0);
                    getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
                }
            }).start();

            // 显示设置成功提示
            Toast.makeText(NotesPreferenceActivity.this,
                    getString(R.string.preferences_toast_success_set_accout, account),
                    Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 移除同步账户，并清理相关的本地同步信息
     */
    private void removeSyncAccount() {
        // 清除账户偏好设置和最后同步时间
        SharedPreferences settings = getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        if (settings.contains(PREFERENCE_SYNC_ACCOUNT_NAME)) {
            editor.remove(PREFERENCE_SYNC_ACCOUNT_NAME);
        }
        if (settings.contains(PREFERENCE_LAST_SYNC_TIME)) {
            editor.remove(PREFERENCE_LAST_SYNC_TIME);
        }
        editor.commit();

        // 在后台线程中清除本地Google Tasks相关信息
        new Thread(new Runnable() {
            public void run() {
                ContentValues values = new ContentValues();
                values.put(NoteColumns.GTASK_ID, "");
                values.put(NoteColumns.SYNC_ID, 0);
                getContentResolver().update(Notes.CONTENT_NOTE_URI, values, null, null);
            }
        }).start();
    }

    /**
     * 获取当前同步账户名
     * @param context 上下文
     * @return 当前同步账户名，若无则返回空字符串
     */
    public static String getSyncAccountName(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
                Context.MODE_PRIVATE);
        return settings.getString(PREFERENCE_SYNC_ACCOUNT_NAME, "");
    }

    /**
     * 设置最后同步时间
     * @param context 上下文
     * @param time 最后同步时间的时间戳
     */
    public static void setLastSyncTime(Context context, long time) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong(PREFERENCE_LAST_SYNC_TIME, time);
        editor.commit();
    }

    /**
     * 获取最后同步时间
     * @param context 上下文
     * @return 最后同步时间的时间戳，若无则返回0
     */
    public static long getLastSyncTime(Context context) {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME,
                Context.MODE_PRIVATE);
        return settings.getLong(PREFERENCE_LAST_SYNC_TIME, 0);
    }

    /**
     * 同步状态广播接收器，监听同步状态变化并更新UI
     */
    private class GTaskReceiver extends BroadcastReceiver {

        /**
         * 接收到广播时调用
         * @param context 上下文
         * @param intent 包含同步状态信息的意图
         */
        @Override
        public void onReceive(Context context, Intent intent) {
            // 刷新UI
            refreshUI();
            // 如果正在同步，更新同步状态文本
            if (intent.getBooleanExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_IS_SYNCING, false)) {
                TextView syncStatus = (TextView) findViewById(R.id.prefenerece_sync_status_textview);
                syncStatus.setText(intent
                        .getStringExtra(GTaskSyncService.GTASK_SERVICE_BROADCAST_PROGRESS_MSG));
            }

        }
    }

    /**
     * 处理选项菜单的点击事件
     * @param item 被点击的菜单项
     * @return true表示事件已处理，false表示未处理
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // 点击返回按钮，返回笔记列表活动
                Intent intent = new Intent(this, NotesListActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return true;
            default:
                return false;
        }
    }
}
