package jp.sourceforge.tamanegisoul.sa;

import java.util.Calendar;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;

/**
 * アラーム起動時にAlarmManagerから呼び出されるレシーバー
 */
public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        long alarmId = intent.getExtras().getLong(DBHelper.C_ALARM_ID);
        LogUtil.d("AlarmReceived. AlarmId->%s", alarmId);

        // スヌーズによる起動かどうか
        boolean isSnooze = intent.getExtras().getBoolean("isSnooze");
        // 曜日と休日判定して鳴動要否を判断
        boolean enabled = isSnooze ? true : isAlarmEnabled(context, alarmId);
        LogUtil.d("Alarm enabled->%s", enabled);
        if (enabled) {
            // アラーム鳴動画面を表示
            Intent i = new Intent(context, DoAlarmActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.putExtra(DBHelper.C_ALARM_ID, alarmId);
            context.startActivity(i);
        }
    }

    /**
     * アラーム定義（平日・土日・休日）と今日の日付を比較して、アラームを鳴動するかどうかを判定する。
     * @param context
     * @param alarmId
     * @return 鳴動する場合はtrue
     */
    private boolean isAlarmEnabled(Context context, long alarmId) {
        SQLiteDatabase db = new DBHelper(context).getReadableDatabase();
        // アラーム定義
        Cursor c = db.query(DBHelper.T_ALARM, null, DBHelper.C_ALARM_ID + "=?", new String[] { String.valueOf(alarmId) }, null, null, null);
        if (!c.moveToFirst()) {
            Toast.makeText(context, String.format("Alarm is not found: alarmId->%s", alarmId), Toast.LENGTH_LONG).show();
            LogUtil.d("Alarm is not found: alarmId->%s", alarmId);
            return false;
        }
        boolean isEnabled = c.getInt(c.getColumnIndex(DBHelper.C_ALARM_ENEBLED)) != 0;
        boolean isWeekendEnabled = c.getInt(c.getColumnIndex(DBHelper.C_ALARM_WEEKEND)) != 0;
        boolean isWeekdayEnabled = c.getInt(c.getColumnIndex(DBHelper.C_ALARM_WEEKDAY)) != 0;
        boolean isHolidayEnabled = c.getInt(c.getColumnIndex(DBHelper.C_ALARM_HOLIDAY)) != 0;
        c.close();
        LogUtil.d("Alarm enabled->%s, weekend enabled->%s, weekday enabled->%s, holiday enabled->%s", isEnabled, isWeekendEnabled, isWeekdayEnabled,
                isHolidayEnabled);
        // 今日の曜日
        Calendar today = Calendar.getInstance();
        int day = today.get(Calendar.DAY_OF_WEEK);
        LogUtil.d("day of week(Today)->%s", day);
        // 休日かどうか
        // TODO 日付フォーマットをDBHelperに集約
        c = db.query(DBHelper.T_HOLIDAY, null, DBHelper.C_HOLIDAY_DATE + "=?", new String[] { String.format("%d-%02d-%02d", today.get(Calendar.YEAR),
                today.get(Calendar.MONTH) + 1, today.get(Calendar.DATE)) }, null, null, null);
        boolean isHoliday = c.moveToFirst();
        c.close();
        db.close();
        LogUtil.d("Today is holiday?->%s", isHoliday);

        // 判定
        if (isEnabled) {
            if (isHoliday) {
                return isHolidayEnabled;
            } else if (day == Calendar.SATURDAY || day == Calendar.SUNDAY) {
                return isWeekendEnabled;
            } else {
                return isWeekdayEnabled;
            }
        }

        return false;
    }

}
