package kz.arta.synergy.workflow.mobile.android;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;

import kz.arta.synergy.workflow.mobile.android.authorization.SynergyAccount;
import kz.arta.synergy.workflow.mobile.android.common.SettingsConst;
import kz.arta.synergy.workflow.mobile.android.common.models.Person;
import kz.arta.synergy.workflow.mobile.android.common.offline.SyncMain;
import kz.arta.synergy.workflow.mobile.android.common.requests.SendGetRequest;
import kz.arta.synergy.workflow.mobile.android.common.utils.Utils;
import kz.arta.synergy.workflow.mobile.android.common.utils.Wrapper;

/**
 * Created by neox on 22.08.14.
 * Класс используется для синхронизации по таймеру
 */
public class AlarmManagerSync extends BroadcastReceiver {

    final public static String SYNC = "SYNC";

    @Override
    public void onReceive(final Context context, Intent intent) {
        //получаем extras
        Bundle extras = intent.getExtras();
        // в этом методе происходит обработка события
        if (extras != null && !extras.getBoolean(SYNC, Boolean.FALSE)) {
            // ищем аккаунт в менеджере аккаунтов и запускаем синхронизацию
            AccountManager accountManager = AccountManager.get(context);
            Account[] accounts = accountManager.getAccounts();
            for (Account account : accounts) {
                if (account.type.equals(SynergyAccount.TYPE)) {
                    final Person person = new Person();
                    person.setPassword(accountManager.getPassword(account));
                    person.setLogin(accountManager.getUserData(account, SynergyAccount.LOGIN));
                    person.setHost(accountManager.getUserData(account, SynergyAccount.HOST));
                    person.setShortHost(accountManager.getUserData(account, SynergyAccount.SHORT_HOST));
                    person.setUuid(accountManager.getUserData(account, SynergyAccount.USER_ID));
                    person.setFirstname(accountManager.getUserData(account, SynergyAccount.FIRSTNAME));
                    person.setLastname(accountManager.getUserData(account, SynergyAccount.LASTNAME));
                    // если включен интернет
                    if (Utils.isOnline(context, null) && SyncMain.canSync) {
                        new SendGetRequest("about", person) {
                            @Override
                            protected void onPostExecute(String result) {
                                if (result == null) {
                                    return;
                                }
                                SyncMain offline = new SyncMain(context, person);
                                offline.setShowProgress(false);
                                offline.setAllSync(true);
                                offline.setSend(false);
                                offline.clearTables(false);
                                offline.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                                super.onPostExecute(result);
                            }
                        }.execute();
                    }
                    break;
                }
            }
        }
    }

    public void setAlarm(Context context) {
        SharedPreferences mSettings = context.getSharedPreferences(SettingsConst.DEFAULT_NAME_SETTINGS, Context.MODE_PRIVATE);
        if (mSettings.contains(SettingsConst.PERIOD_MILLISECONDS_SYNC) &&
                !mSettings.getString(SettingsConst.PERIOD_MILLISECONDS_SYNC, "").equals(Wrapper.NO_ERROR)) {
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent intent = new Intent(context, AlarmManagerSync.class);
            intent.putExtra(SYNC, Boolean.FALSE);
            PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
            am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(),
                    Integer.parseInt(mSettings.getString(SettingsConst.PERIOD_MILLISECONDS_SYNC, "")), pi);
        }
    }

    public void cancelAlarm(Context context) {
        Intent intent = new Intent(context, AlarmManagerSync.class);
        PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(sender);
    }
}