package jp.sourceforge.tamanegisoul.sa;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

/**
 * アラーム鳴動画面
 */
public class DoAlarmActivity extends Activity {

    private Window mWindow;
    private MediaPlayer mRingtone;
    private Vibrator mVibrator;
    private BroadcastReceiver mReceiver;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        LogUtil.d("DoAlarmActivity called.");
        super.onCreate(savedInstanceState);

        // スクリーンオフ操作された時にスヌーズするためにReceiverを利用
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LogUtil.d("onReceive()");
                snooze();
            }
        };
        registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));

        // アラーム用の音量設定を使用
        setVolumeControlStream(AudioManager.STREAM_ALARM);

        // スクリーンロックを解除
        // KeyguardLockとPowerManagerを使う方法はスクリーンロックが解除できなかったので、このやり方で。
        requestWindowFeature(android.view.Window.FEATURE_NO_TITLE);
        mWindow = getWindow();
        mWindow.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        mWindow.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);

        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
        mRingtone = new MediaPlayer();

        setContentView(R.layout.do_alarm);

        ((Button) findViewById(R.id.stop_button)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        // スヌーズボタン
        Button snoozeButton = (Button) findViewById(R.id.snooze_button);
        final boolean isSnoozeSet = !PreferenceManager.getDefaultSharedPreferences(DoAlarmActivity.this).getString("snooze", "").equals("");
        snoozeButton.setEnabled(isSnoozeSet);
        // デバッグ画面用
        if (getIntent().getExtras() == null) {
            snoozeButton.setEnabled(false);
        }
        snoozeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                snooze();
            }
        });
        LogUtil.d("DoAlarmActivity created.");
    }

    @Override
    public void onStart() {
        super.onStart();

        // バイブレーター
        long[] vibratorPattern = PreferenceUtils.getVibratorPattern(this);
        if (vibratorPattern != null) {
            mVibrator.vibrate(vibratorPattern, 0);
        }

        // アラーム音
        Uri ringtoneUri = PreferenceUtils.getRingtone(this);
        if (ringtoneUri != null) {
            mRingtone.reset();
            try {
                mRingtone.setDataSource(this, ringtoneUri);
                // ↓これでアラームの音量設定が使われる
                mRingtone.setAudioStreamType(AudioManager.STREAM_ALARM);
                mRingtone.setLooping(true);
                mRingtone.prepare();
                mRingtone.start();
            } catch (Exception e) {
                Toast.makeText(this, "Failed to ring", Toast.LENGTH_LONG).show();
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mReceiver);
        mVibrator.cancel();
        mRingtone.stop();
        mRingtone.release();
        // スクリーンロックを戻す(これに意味があるかは？)
        mWindow.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
        mWindow.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON);
    }

    @Override
    protected void onUserLeaveHint() {
        // ホームキー押下で呼ばれる
        snooze();
        super.onUserLeaveHint();
    }

    @Override
    public void onBackPressed() {
        // 戻るボタン押下で呼ばれる
        snooze();
    }

    private void snooze() {
        String minute = PreferenceManager.getDefaultSharedPreferences(DoAlarmActivity.this).getString("snooze", "");
        if (!minute.equals("")) {
            // 設定時刻
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE, Integer.parseInt(minute));
            // アラーム設定
            Intent intent = new Intent(DoAlarmActivity.this, AlarmReceiver.class);
            long alarmId = getIntent().getExtras().getLong(DBHelper.C_ALARM_ID);
            intent.setData(Uri.parse("http://sourceforge.jp/projects/schedulealarm/alarm/snooze/" + alarmId));
            intent.putExtra(DBHelper.C_ALARM_ID, alarmId);
            intent.putExtra("isSnooze", true);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(DoAlarmActivity.this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
        }
        finish();
    }

}
