package jp.sourceforge.tamanegisoul.sa.action;

import java.util.Date;

import jp.sourceforge.tamanegisoul.sa.R;
import jp.sourceforge.tamanegisoul.sa.util.AppAlarmManager;
import jp.sourceforge.tamanegisoul.sa.util.DBHelper;
import jp.sourceforge.tamanegisoul.sa.util.FormatUtils;
import jp.sourceforge.tamanegisoul.sa.widget.NationalHolidayQueryProgressDialog;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/**
 * 休日一覧画面
 */
public class HolidayListActivity extends ListActivity {

    private static final int MENU_ADD = 1; // 追加メニュー
    private static final int MENU_ADD_NATIONAL_HOLIDAY = 2; // 祝日追加メニュー
    private static final int MENU_REMOVE_ALL = 3; // 全削除メニュー

    private Cursor mCursor; // ListViewのデータカーソル

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

        SQLiteDatabase db = new DBHelper(this).getReadableDatabase();
        mCursor = db.query(DBHelper.T_HOLIDAY, null, null, null, null, null, DBHelper.C_HOLIDAY_DATE);

        // リストの設定
        SimpleCursorAdapter ca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, mCursor, new String[] { DBHelper.C_HOLIDAY_DATE, DBHelper.C_HOLIDAY_NAME }, new int[] { android.R.id.text1, android.R.id.text2 });
        ca.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
                String text = null;
                Date d = FormatUtils.parseDate(cursor.getString(cursor.getColumnIndex(DBHelper.C_HOLIDAY_DATE)));
                if (view.getId() == android.R.id.text2) {
                    // タイトル表示
                    text = cursor.getString(cursor.getColumnIndex(DBHelper.C_HOLIDAY_NAME));
                } else if (view.getId() == android.R.id.text1) {
                    // 日時表示
                    text = FormatUtils.formatDateDisplay(d);
                }
                ((TextView) view).setText(text);
                // 過去日付はグレーアウト
                if (FormatUtils.formatDate(d).compareTo(FormatUtils.formatDate(new Date())) < 0) {
                    ((TextView) view).setTextColor(Color.DKGRAY);
                } else {
                    ((TextView) view).setTextColor(Color.WHITE);
                }
                return true;
            }
        });
        setListAdapter(ca);

        // リスト項目の選択リスナー
        getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 休日IDを渡して休日設定画面を起動
                Intent i = new Intent(parent.getContext(), HolidayActivity.class);
                i.putExtra(DBHelper.C_HOLIDAY_ID, mCursor.getInt(mCursor.getColumnIndex(DBHelper.C_HOLIDAY_ID)));
                startActivity(i);
            }
        });

        // 追加ボタン
        ((Button) findViewById(R.id.add_holiday_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // 休日IDを渡さずに休日設定画面を起動
                startActivity(new Intent(HolidayListActivity.this, HolidayActivity.class));
            }
        });
        // 祝日取得ボタン
        ((Button) findViewById(R.id.get_national_holiday_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // プログレスダイアログ
                NationalHolidayQueryProgressDialog dialog = new NationalHolidayQueryProgressDialog(HolidayListActivity.this);
                dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialog) {
                        validateList();
                        // 祝日定義が変わったのでアラーム更新
                        AppAlarmManager.getInstance(HolidayListActivity.this).refreshAlarm();
                    }
                });
                dialog.show();
            }
        });
        // 削除ボタン
        ((Button) findViewById(R.id.remove_all_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                AlertDialog d = new AlertDialog.Builder(HolidayListActivity.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) {
                        SQLiteDatabase db = new DBHelper(HolidayListActivity.this).getWritableDatabase();
                        db.delete(DBHelper.T_HOLIDAY, null, null);
                        db.close();
                        validateList();
                        dialog.dismiss();
                    }
                });
                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();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();
        validateList();
    }

    private void validateList() {
        mCursor.requery();
        // 次の祝日をリストに表示する
        mCursor.moveToFirst();
        Date now = new Date();
        while (mCursor.moveToNext()) {
            Date d = FormatUtils.parseDate(mCursor.getString(mCursor.getColumnIndex(DBHelper.C_HOLIDAY_DATE)));
            if (d.after(now))
                break;
        }
        setSelection(mCursor.getPosition());
        mCursor.moveToNext();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mCursor.close();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuItem menuItem = menu.add(Menu.NONE, MENU_ADD, Menu.NONE, "追加");
        menuItem.setIcon(android.R.drawable.ic_menu_add);

        menuItem = menu.add(Menu.NONE, MENU_ADD_NATIONAL_HOLIDAY, Menu.NONE, "祝日を取得");
        menuItem.setIcon(R.drawable.ic_menu_refresh);

        menuItem = menu.add(Menu.NONE, MENU_REMOVE_ALL, Menu.NONE, "すべて削除");
        menuItem.setIcon(android.R.drawable.ic_menu_delete);

        return super.onCreateOptionsMenu(menu);
    }
}
