package jp.sourceforge.tamanegisoul.sa.action;

import java.util.Calendar;
import java.util.Date;

import jp.sourceforge.tamanegisoul.sa.R;
import jp.sourceforge.tamanegisoul.sa.util.AppAccountManager;
import jp.sourceforge.tamanegisoul.sa.util.AppAlarmManager;
import jp.sourceforge.tamanegisoul.sa.util.DBHelper;
import jp.sourceforge.tamanegisoul.sa.util.FormatUtils;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.CalendarContract.Calendars;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;

/**
 * Googleカレンダーのイベント編集画面
 */
public class CalendarEventActivity extends Activity {

    private Long mItemId;

    private DatePicker mDatePicker;
    private TimePicker mTimePicker;
    private EditText mNameText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calendar_event);
        initWidget();

        // Intentを取得(更新の場合はidを受け取る)
        Intent i = getIntent();
        mItemId = i.hasExtra(DBHelper.C_CALENDAR_ID) ? i.getExtras().getLong(DBHelper.C_CALENDAR_ID) : null;
        if (mItemId != null) {
            bindDataToView();
        }
        // 削除ボタンの有効化
        ((Button) findViewById(R.id.removeButton)).setEnabled(mItemId != null);
    }

    private void initWidget() {
        // インスタンス変数に
        Calendar cal = Calendar.getInstance();
        mDatePicker = (DatePicker) findViewById(R.id.datePicker);
        mDatePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH), new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar cal = Calendar.getInstance();
                cal.set(Calendar.YEAR, year);
                cal.set(Calendar.MONTH, monthOfYear);
                cal.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                ((TextView) findViewById(R.id.day_of_week)).setText(FormatUtils.formatDayOfWeek(cal.getTime()));
            }
        });
        // 変更イベントを起こして曜日表示を更新するために…
        mDatePicker.updateDate(cal.get(Calendar.YEAR) + 1, cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
        mDatePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH));
        mTimePicker = (TimePicker) findViewById(R.id.timePicker);
        mTimePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(this));
        mNameText = (EditText) findViewById(R.id.name);
        // Buttonのリスナー登録
        ((RadioGroup) findViewById(R.id.alarm_add_or_remove)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.alarm_add) {
                    mTimePicker.setEnabled(true);
                    ((TextView) findViewById(R.id.event_name_suffix)).setText("+alarm");
                } else if (checkedId == R.id.alarm_remove) {
                    mTimePicker.setEnabled(false);
                    ((TextView) findViewById(R.id.event_name_suffix)).setText("-alarm");
                } else if (checkedId == R.id.alarm_replace) {
                    mTimePicker.setEnabled(true);
                    ((TextView) findViewById(R.id.event_name_suffix)).setText("#alarm");
                }
            }
        });
        ((Button) findViewById(R.id.setButton)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                save();
                finish();
            }
        });
        ((Button) findViewById(R.id.removeButton)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog d = new AlertDialog.Builder(CalendarEventActivity.this).create();
                d.setMessage("削除しますか？\n削除後、すこし遅れて反映されます。");
                d.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        remove();
                        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() {
        Cursor cursor = getContentResolver().query(DBHelper.URI_CALENDAR_EVENTS, new String[] { "_id", "title", "dtstart", "allDay" }, DBHelper.C_EVENTS_ID + "=?", new String[] { String.valueOf(mItemId) }, null);
        cursor.moveToFirst();
        Calendar cal = Calendar.getInstance();
        Date date = new Date(cursor.getLong(cursor.getColumnIndex(DBHelper.C_CALENDAR_START)));
        cal.setTime(date);
        mDatePicker.updateDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE));
        mTimePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
        mTimePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
        if (cursor.getString(cursor.getColumnIndex(DBHelper.C_CALENDAR_TITLE)).contains("+alarm")) {
            ((RadioButton) findViewById(R.id.alarm_add)).setChecked(true);
        } else if (cursor.getString(cursor.getColumnIndex(DBHelper.C_CALENDAR_TITLE)).contains("-alarm")) {
            ((RadioButton) findViewById(R.id.alarm_remove)).setChecked(true);
        } else if (cursor.getString(cursor.getColumnIndex(DBHelper.C_CALENDAR_TITLE)).contains("#alarm")) {
            ((RadioButton) findViewById(R.id.alarm_replace)).setChecked(true);
        }
        String title = cursor.getString(cursor.getColumnIndex(DBHelper.C_CALENDAR_TITLE));
        mNameText.setText(title.substring(0, title.length() - 6));
    }

    /**
     * 現在の設定値をDBに保存する。
     */
    private void save() {
        Cursor calendarCursor = managedQuery(DBHelper.URI_CALENDAR_CALENDARS, new String[] { "_id" }, "ownerAccount=?", new String[] { AppAccountManager.getInstance(this).getAccount().name }, null);
        calendarCursor.moveToFirst();
        long calendarId = calendarCursor.getLong(0);
        Calendar dateTime = Calendar.getInstance();
        dateTime.set(Calendar.YEAR, mDatePicker.getYear());
        dateTime.set(Calendar.MONTH, mDatePicker.getMonth());
        dateTime.set(Calendar.DAY_OF_MONTH, mDatePicker.getDayOfMonth());
        dateTime.set(Calendar.HOUR_OF_DAY, mTimePicker.getCurrentHour());
        dateTime.set(Calendar.MINUTE, mTimePicker.getCurrentMinute());
        dateTime.set(Calendar.SECOND, 0);
        dateTime.set(Calendar.MILLISECOND, 0);
        ContentValues v = new ContentValues();
        v.put("calendar_id", calendarId);
        v.put(DBHelper.C_CALENDAR_TITLE, mNameText.getText().toString() + ((TextView) findViewById(R.id.event_name_suffix)).getText());
        v.put(DBHelper.C_CALENDAR_START, dateTime.getTimeInMillis());
        v.put(DBHelper.C_CALENDAR_END, dateTime.getTimeInMillis() + 1000 * 60);
        v.put(DBHelper.C_CALENDAR_ALLDAY, ((RadioButton) findViewById(R.id.alarm_remove)).isChecked() ? 1 : 0);
        Uri u = DBHelper.URI_CALENDAR_EVENTS;
        if (Build.VERSION.SDK_INT >14) {
        	u = u.buildUpon().appendQueryParameter(android.provider.CalendarContract.CALLER_IS_SYNCADAPTER,"true")
        	        .appendQueryParameter(Calendars.ACCOUNT_NAME, AppAccountManager.getInstance(this).getAccount().name)
        	        .appendQueryParameter(Calendars.ACCOUNT_TYPE, AppAccountManager.getInstance(this).getAccount().type)
        			.build();
        	 }
        if (mItemId == null) {
            Uri a = getContentResolver().insert(u, v);
            a.toString();
        } else {
            getContentResolver().update(ContentUris.withAppendedId(DBHelper.URI_CALENDAR_EVENTS, mItemId), v, null, null);
        }
        // イベントが変わったのでアラーム更新
        AppAlarmManager.getInstance(CalendarEventActivity.this).refreshAlarm();
    }
    
    /**
     * 現在の設定値を削除する。
     */
    private void remove() {
        if (mItemId != null) {
            getContentResolver().delete(ContentUris.withAppendedId(DBHelper.URI_CALENDAR_EVENTS, mItemId), null, null);
            // イベントが変わったのでアラーム更新
            AppAlarmManager.getInstance(CalendarEventActivity.this).refreshAlarm();
        }
    }
}
