package jp.sourceforge.tamanegisoul.sa;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TimePicker;

/**
 * アラーム設定画面 起動時のIntentには、アラームIDを受けとる。 これが設定されていればアラーム更新、設定されていなければ新規アラーム作成。
 */
public class AlarmActivity extends Activity {

    private DBHelper mDbHelper;
    private Integer mAlarmId; // 編集対象のアラームID(新規作成のときはnull)

    private TimePicker mTimePicker;
    private CompoundButton mEnabledCheck;
    private CompoundButton mWeekdayCheck;
    private CompoundButton mWeekendCheck;
    private CompoundButton mHolidayCheck;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 初期化
        super.onCreate(savedInstanceState);
        mDbHelper = new DBHelper(this);
        setContentView(R.layout.alarm);
        setTitle(getResources().getString(R.string.set_alarm));
        initWidget();

        // Intentを取得(更新の場合はidを受け取る)
        Intent i = getIntent();
        mAlarmId = i.hasExtra(DBHelper.C_ALARM_ID) ? i.getExtras().getInt(DBHelper.C_ALARM_ID) : null;
        if (mAlarmId != null) {
            bindDataToView();
        }
        LogUtil.d("AlarmActivity created. alarmId->%s", mAlarmId);
    }

    private void initWidget() {
        // インスタンス変数に
        mTimePicker = (TimePicker) findViewById(R.id.timePicker);
        mTimePicker.setIs24HourView(true);
        mEnabledCheck = (CompoundButton) findViewById(R.id.enabledCheck);
        mWeekdayCheck = (CompoundButton) findViewById(R.id.weekdayCheck);
        mWeekendCheck = (CompoundButton) findViewById(R.id.weekendCheck);
        mHolidayCheck = (CompoundButton) findViewById(R.id.holidayCheck);
        // Buttonのリスナー登録
        ((Button) findViewById(R.id.setButton)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                long rowId = saveAlarm();
                if (mEnabledCheck.isChecked()) {
                    turnOnAlarm(rowId);
                }
                finish();
            }
        });
        ((Button) findViewById(R.id.removeButton)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog d = new AlertDialog.Builder(AlarmActivity.this).create();
                d.setMessage(getResources().getString(R.string.confirm_delete));
                d.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        removeAlarm();
                        turnOffAlarm(mAlarmId);
                        dialog.dismiss();
                        finish();
                    }
                });
                d.setButton(AlertDialog.BUTTON_NEGATIVE, getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                d.show();
            }
        });
    }

    /**
     * DBの内容をViewに反映する。
     */
    private void bindDataToView() {
        SQLiteDatabase db = mDbHelper.getReadableDatabase();
        Cursor c = db.query(DBHelper.T_ALARM, null, DBHelper.C_ALARM_ID + "=?", new String[] { mAlarmId.toString() }, null, null, null);
        c.moveToFirst();
        mTimePicker.setCurrentHour(c.getInt(c.getColumnIndex(DBHelper.C_ALARM_HOUR)));
        mTimePicker.setCurrentMinute(c.getInt(c.getColumnIndex(DBHelper.C_ALARM_MINUTE)));
        mEnabledCheck.setChecked(c.getInt(c.getColumnIndex(DBHelper.C_ALARM_ENEBLED)) == 1);
        mWeekdayCheck.setChecked(c.getInt(c.getColumnIndex(DBHelper.C_ALARM_WEEKDAY)) == 1);
        mWeekendCheck.setChecked(c.getInt(c.getColumnIndex(DBHelper.C_ALARM_WEEKEND)) == 1);
        mHolidayCheck.setChecked(c.getInt(c.getColumnIndex(DBHelper.C_ALARM_HOLIDAY)) == 1);
        db.close();
    }

    /**
     * 現在の設定値をDBに保存する。
     */
    private long saveAlarm() {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        ContentValues v = new ContentValues();
        v.put(DBHelper.C_ALARM_HOUR, mTimePicker.getCurrentHour());
        v.put(DBHelper.C_ALARM_MINUTE, mTimePicker.getCurrentMinute());
        v.put(DBHelper.C_ALARM_ENEBLED, mEnabledCheck.isChecked());
        v.put(DBHelper.C_ALARM_WEEKDAY, mWeekdayCheck.isChecked());
        v.put(DBHelper.C_ALARM_WEEKEND, mWeekendCheck.isChecked());
        v.put(DBHelper.C_ALARM_HOLIDAY, mHolidayCheck.isChecked());

        long rowId;
        if (mAlarmId == null) {
            rowId = db.insert(DBHelper.T_ALARM, null, v);
        } else {
            v.put(DBHelper.C_ALARM_ID, mAlarmId);
            rowId = db.replace(DBHelper.T_ALARM, null, v);
        }
        db.close();
        return rowId;
    }

    /**
     * 現在の設定値を削除する。
     */
    private void removeAlarm() {
        SQLiteDatabase db = mDbHelper.getWritableDatabase();
        db.delete(DBHelper.T_ALARM, DBHelper.C_ALARM_ID + "=?", new String[] { String.valueOf(mAlarmId) });
        db.close();
    }

    /**
     * AndroidのAlarmManagerにアラームを設定する。
     * @param alarmId
     */
    private void turnOnAlarm(long alarmId) {
        // 設定時刻
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, mTimePicker.getCurrentHour());
        calendar.set(Calendar.MINUTE, mTimePicker.getCurrentMinute());
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        if (calendar.getTimeInMillis() < Calendar.getInstance().getTimeInMillis()) {
            // 設定日時が現在より前の場合は、アラームを明日から起動にしないと、
            // setRepeatingの直後に起動してしまう。
            calendar.add(Calendar.DATE, 1);
        }

        // アラーム設定
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.putExtra(DBHelper.C_ALARM_ID, alarmId);
        intent.setData(Uri.parse("http://sourceforge.jp/projects/schedulealarm/alarm/" + alarmId));
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
    }

    /**
     * AndroidのAlarmManagerのアラームを解除する。
     * @param alarmId
     */
    private void turnOffAlarm(long alarmId) {
        Intent intent = new Intent(this, AlarmReceiver.class);
        intent.setData(Uri.parse("http://sourceforge.jp/projects/schedulealarm/alarm/" + alarmId));
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.cancel(PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
    }

}
