package jp.sourceforge.tamanegisoul.sa.util;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;

/**
 * アカウント管理クラス。
 */
public class AppAccountManager {

    private static AppAccountManager sSingleton;

    public static synchronized AppAccountManager getInstance(Context context) {
        if (sSingleton == null)
            sSingleton = new AppAccountManager(context);
        return sSingleton;
    }

    private Context mContext;
    private AccountManager mAccountManager;

    private AppAccountManager(Context context) {
        super();
        mContext = context;
        mAccountManager = AccountManager.get(mContext);
    }

    /**
     * @return 現在選択されているアカウント。未選択の場合はnull。
     */
    public Account getAccount() {
        String accountName = PreferenceUtils.getString(mContext, PreferenceUtils.KEY_ACCOUNT);
        if (accountName != null) {
            for (Account item : mAccountManager.getAccountsByType("com.google")) {
                if (item.name.equals(accountName)) {
                    return item;
                }
            }
        }
        return null;
    }

    /**
     * @return 登録されているアカウント名の一覧
     */
    public String[] getAccountNames() {
        Account[] accounts = mAccountManager.getAccountsByType("com.google");
        String[] accountNames = new String[accounts.length];
        for (int i = 0; i < accounts.length; i++) {
            accountNames[i] = accounts[i].name;
        }
        return accountNames;
    }
}
