package jp.sourceforge.tamanegisoul.sa;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

/**
 * アラーム一覧画面。 これがトップ画面。
 */
public class AlarmListActivity extends ListActivity {

    private static final int MENU_ADD = 1; // アラーム追加メニュー
    private static final int MENU_HOLIDAY = 2; // 休日設定メニュー
    private static final int MENU_PREFERENCE = 3; // 設定メニュー
    private static final int MENU_ABOUT = 8; // Aboutメニュー
    private static final int MENU_DEBUG = 9; // デバッグメニュー

    private SQLiteDatabase mDataBase;
    private Cursor mCursor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 初期化
        super.onCreate(savedInstanceState);
        setContentView(R.layout.alarm_list);
        mDataBase = new DBHelper(this).getReadableDatabase();
        mCursor = mDataBase.query(DBHelper.T_ALARM, null, null, null, null, null, null);

        // リストビューを設定
        SimpleCursorAdapter ca = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, mCursor, new String[] { DBHelper.C_ALARM_HOUR,
                DBHelper.C_ALARM_MINUTE }, 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;
                if (view.getId() == android.R.id.text1) {
                    // 時刻表記
                    text = String.format("%02d:%02d", cursor.getInt(cursor.getColumnIndex(DBHelper.C_ALARM_HOUR)), cursor.getInt(cursor
                            .getColumnIndex(DBHelper.C_ALARM_MINUTE)));
                } else if (view.getId() == android.R.id.text2) {
                    // 設定表記
                    // TODO リテラルを外部化
                    StringBuilder b = new StringBuilder();
                    b.append(cursor.getInt(cursor.getColumnIndex(DBHelper.C_ALARM_ENEBLED)) == 1 ? "有効 " : "無効 ");
                    b.append(cursor.getInt(cursor.getColumnIndex(DBHelper.C_ALARM_WEEKDAY)) == 1 ? "平日 " : "");
                    b.append(cursor.getInt(cursor.getColumnIndex(DBHelper.C_ALARM_WEEKEND)) == 1 ? "土日 " : "");
                    b.append(cursor.getInt(cursor.getColumnIndex(DBHelper.C_ALARM_HOLIDAY)) == 1 ? "祝日 " : "");
                    text = b.toString();
                }
                ((TextView) view).setText(text);
                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(), AlarmActivity.class);
                i.putExtra(DBHelper.C_ALARM_ID, mCursor.getInt(mCursor.getColumnIndex(DBHelper.C_ALARM_ID)));
                startActivity(i);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        // リストの表示を更新
        mCursor.requery();
        // 初回起動時は設定を促す
        if (PreferenceUtils.getRingtone(this) == null && PreferenceUtils.getVibratorPattern(this) == null) {
            Resources r = getResources();
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
            alertDialog.setMessage(r.getString(R.string.please_set_preferences));
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, r.getString(android.R.string.ok), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    startActivity(new Intent(AlarmListActivity.this, AppPreferenceActivity.class));
                }
            });
            alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, r.getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
    }

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, MENU_ADD, Menu.NONE, R.string.add_alarm).setIcon(android.R.drawable.ic_menu_add);
        menu.add(Menu.NONE, MENU_HOLIDAY, Menu.NONE, R.string.menu_holiday).setIcon(android.R.drawable.ic_menu_my_calendar);
        menu.add(Menu.NONE, MENU_PREFERENCE, Menu.NONE, R.string.preference).setIcon(android.R.drawable.ic_menu_preferences);
        menu.add(Menu.NONE, MENU_ABOUT, Menu.NONE, R.string.about).setIcon(android.R.drawable.ic_menu_info_details);
        menu.add(Menu.NONE, MENU_DEBUG, Menu.NONE, R.string.debug).setIcon(android.R.drawable.ic_menu_manage);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ADD:
            // アラームIDを渡さずにアラーム画面を表示
            startActivity(new Intent(this, AlarmActivity.class));
            break;
        case MENU_HOLIDAY:
            startActivity(new Intent(this, HolidayListActivity.class));
            break;
        case MENU_PREFERENCE:
            startActivity(new Intent(this, AppPreferenceActivity.class));
            break;
        case MENU_ABOUT:
            showAboutDialog();
            break;
        case MENU_DEBUG:
            startActivity(new Intent(this, MainActivity.class));
            break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    private void showAboutDialog() {
        String versionName;
        try {
            PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA);
            versionName = packageInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            versionName = "不明";
        }
        AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        alertDialog.setMessage(String.format("現在のバージョン：%s\n最新を確認しますか？", versionName));
        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getResources().getString(android.R.string.ok), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://sourceforge.jp/projects/schedulealarm/releases/")));
            }
        });
        alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getResources().getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        alertDialog.show();
    }

}
