package com.csi.puchipuchi;


import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;


public class PuchipuchiActivity extends Activity {
    private SharedPreferences sp;
	private MediaPlayer player;
	private Thread mainLoop = null;// スレッドクラス
	private int original_vol;
	private AudioManager am;
	private NotificationManager mNM;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new DrawSurfaceView(this));

        //スリープから復帰させる
    	PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
    	PowerManager.WakeLock wakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK
    			| PowerManager.ACQUIRE_CAUSES_WAKEUP
    			| PowerManager.ON_AFTER_RELEASE, "Your App Tag");
		wakelock.acquire();

		sp = getSharedPreferences("com.csi.puchipuchi_preferences", MODE_PRIVATE);
		int volume = sp.getInt("seekbar", 10);

		am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		original_vol = am.getStreamVolume(AudioManager.STREAM_MUSIC);
		int volmax = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		am.setStreamVolume(AudioManager.STREAM_MUSIC, volmax*volume/10, 0); //音量設定

		String url = sp.getString("ringtone_key", "");

		if(url != ""){
			player = MediaPlayer.create(getApplicationContext(), Uri.parse(url));
			player.setLooping(true);
			player.seekTo(0);
			player.start();
		}

		//ロック画面の上に表示させる
	    getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);

	    //アラームONをノティフィケーションで通知
	    mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
	    Notification notification;
	    notification = new Notification(R.drawable.icon, getText(R.string.app_name), System.currentTimeMillis());
	    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
	                   new Intent(this, com.csi.puchipuchi.PuchipuchiActivity.class),
	                   Intent.FLAG_ACTIVITY_NEW_TASK);
	    notification.setLatestEventInfo(this,
	    								getText(R.string.app_name),
	    								getText(R.string.alarm_notifi), contentIntent);
	    mNM.notify(0, notification);

		wakelock.release();
    }

/*
	@Override
	protected void onPause() {
	  super.onPause();
	}
*/
	@Override
	protected void onResume() {
	  super.onResume();
	}

    @Override
    public void onDestroy() {
    	super.onDestroy();
    	if(player != null)    	player.stop();	//再生停止
    	SharedPreferences.Editor editor = sp.edit();
        editor.putBoolean("checkbox1_key", false);
        editor.commit();
        am.setStreamVolume(AudioManager.STREAM_MUSIC, original_vol, 0); //音量を元に戻す
	    mNM.cancel(0);//ノティフィケーション解除
	    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON |
                WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    	Thread.interrupted();	//スレッド終了
    }

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if(event.getAction() == KeyEvent.ACTION_DOWN) {
			switch(event.getKeyCode()){
				case KeyEvent.KEYCODE_BACK:// BACKキー無効化
				case KeyEvent.KEYCODE_VOLUME_DOWN:
				case KeyEvent.KEYCODE_VOLUME_UP:
					return true;
			}
		}
		return super.dispatchKeyEvent(event);
	}


    // SurfaceView Start
    // SurfaceViewを描画するクラス
    class DrawSurfaceView extends SurfaceView implements SurfaceHolder.Callback, Runnable{
    	public Bitmap bmp_off;
    	public Bitmap bmp_on;
		public int m_touch_chk[][] = new int[20][20];
    	public int m_x_offset, m_y_offset, m_for_x, m_for_y, m_bmp_x, m_bmp_y;

    	public DrawSurfaceView(Context context) {
    		super(context);

    		// SurfaceView描画に用いるコールバックを登録する。
    		getHolder().addCallback(this);
//    		getHolder().setFixedSize(getWidth(), getHeight());
    		// スレッド開始
    		mainLoop = new Thread(this);
    		mainLoop.start();
    	}

    	// タッチイベントを処理するためOverrideする
    	@Override
    	public boolean onTouchEvent(MotionEvent event) {
    		// 移動する方向を反転させる
    		// onTouchEventでは、以下の動きをとらえる事ができる
    		//  [ACTION_DOWN] [ACTION_UP] [ACTION_MOVE] [ACTION_CANCEL]
    		// 今回はACTION_DOWN(タッチパネルが押されたとき)に、反応する
    		switch ( event.getAction() )
    		{
    		case MotionEvent.ACTION_DOWN:

    			Vibrator vibrator = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);

    			int touch_x = (int)event.getX();
    			int touch_y = (int)event.getY();

    			int x, y, max, count;

    			max = m_for_y * m_for_x;
    			count = 0;
        		for(y=0; y<m_for_y; y++){
            		for(x=0; x<m_for_x; x++){
		    			if( (m_x_offset*(x+1)+(m_bmp_x*x) <= touch_x) && (touch_x < m_x_offset*(x+1)+(m_bmp_x*(x+1))) ){
		        			if( (m_y_offset*(y+1)+(m_bmp_y*y) <= touch_y) && (touch_y < m_y_offset*(y+1)+(m_bmp_y*(y+1))) ){
		        				if(m_touch_chk[x][y] == 0){
		        					m_touch_chk[x][y] = 1;
		        					vibrator.vibrate(100);
		        				}
		        			}
		    			}
        				if(m_touch_chk[x][y] == 1){
        					count++;
        					if(count==max){
        				    	if(player != null)    	player.stop();
        				    	finish();
        					}
        				}
            		}
        		}

    			break;
    		default:
    			break;
    		}
    		return true;
    	}

    	@Override
    	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    		// TODO 今回は何もしない。
    	}

    	@Override
    	public void surfaceCreated(SurfaceHolder holder) {
    		// SurfaceView生成時に呼び出されるメソッド。
    		int x, y;

    		//常にメディアの音量調整を可能にする
    		setVolumeControlStream(AudioManager.STREAM_MUSIC);

        	BitmapFactory.Options opt = new BitmapFactory.Options();
        	opt.inScaled = false;
        	bmp_off = BitmapFactory.decodeResource(getResources(), R.drawable.puchi_before, opt);
        	bmp_on = BitmapFactory.decodeResource(getResources(), R.drawable.puchi_after, opt);

    		m_bmp_x = bmp_off.getWidth();		//画像の横サイズ
    		m_bmp_y = bmp_off.getHeight();	//画像の縦サイズ

    		x = getWidth();					//画面の横サイズ
    		y = getHeight();				//画面の縦サイズ

    		if(sp!=null){
	    		String param = sp.getString("list_key", "");
	    		if(param == null)	param = "3";
	    		else if(param.equals(""))	param = "3";
	    		Editor editor = sp.edit();
	    		editor.putString("list_key", param);
	    		editor.commit();
	    		m_for_x = m_for_y = Integer.parseInt(param);
    		}else{
    			m_for_x = m_for_y = 3;
    		}

    		m_x_offset = m_bmp_x * m_for_x;		//画像横サイズ * 表示数
    		m_x_offset = x - m_x_offset;		// 残り画面サイズ
    		m_x_offset = m_x_offset / (m_for_x + 1);

    		m_y_offset = m_bmp_y * m_for_y;		//画像横サイズ * 表示数
    		m_y_offset = y - m_y_offset;		// 残り画面サイズ
    		m_y_offset = m_y_offset / (m_for_y + 1);
    	}

    	@Override
    	public void surfaceDestroyed(SurfaceHolder holder) {
    		// TODO 今回は何もしない。
    	}

        @Override
        public void run() {
        	// Runnableインターフェースをimplementsしているので、runメソッドを実装する
        	// これは、Threadクラスのコンストラクタに渡すために用いる。
        	while (true) {

        		try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {

                }

        		Canvas canvas = getHolder().lockCanvas();
        		if (canvas != null) {
        			int x, y;

        			canvas.drawColor(Color.BLACK);

//        			Log.d("test", String.valueOf(m_bmp_x));
//        			Log.d("test", String.valueOf(m_x_offset));

            		for(y=0; y<m_for_y; y++){
                		for(x=0; x<m_for_x; x++){
            				canvas.drawBitmap(getStatusBmp(x, y), m_x_offset * (x+1)+(x*m_bmp_x), m_y_offset * (y+1)+(y*m_bmp_y), null);
                		}
            		}

        			getHolder().unlockCanvasAndPost(canvas);
        		}

        	}
        }

        Bitmap getStatusBmp(int x, int y){
        	//タッチ状態による画像の選択
        	int judge;

        	judge = m_touch_chk[x][y];

        	if(judge == 0){
        		return bmp_off;
        	}else{
        		return bmp_on;
        	}

        }
    } // SurfaceView End


}