package library.core.mainAI;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import library.core.debug.CoreLog;
import library.core.mainAI.R;
import library.core.object.CoreObjectFactory;
import library.core.object.CoreTextObjectFactory;
import library.core.screen.CoreScreen;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;

public abstract class CoreActivity extends Activity implements Runnable,OnTouchListener{


	private ScheduledThreadPoolExecutor schedule = new ScheduledThreadPoolExecutor(1);

	private long time=0;

	public CoreObjectFactory objectFactory;	//オブジェクトの作成用
	public CoreTextObjectFactory textObjectFactory;

	private WakeLock wakeLock;

	protected CoreScreen screen;

	protected abstract void update(float deltaTime);
	/**
	 * 自身で実装するタッチイベント部分
	 * @param event
	 */
	protected abstract void touch(MotionEvent event);
	/**
	 * ＳＥのロードはあらかじめ行わないといけない
	 */
	protected abstract void loadSe();

	/**
	 * スクリーンのロード終了時に呼ばれる　これが呼ばれた後からでしか、screenから正確な画面サイズがとれない
	 */
	protected abstract void screenLoadEnd();

	/**
	 * screenLoadEnd()を抽象クラスにしてそれを外部から呼ぶためのクッション
	 * @author 貴裕
	 *
	 */
	public class ScreenLoadEndRecieve{
		public void sendLoadEnd(){

			if(!RiverCrossingAI.screenLoad){
				RiverCrossingAI.screenLoad=true;
				time=System.currentTimeMillis();
				screenLoadEnd();
			}
		}
	}




	@Override
	protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);

			requestWindowFeature(Window.FEATURE_NO_TITLE);
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

			setContentView(R.layout.activity_main);


			CoreLog.debug("coreActivity create");

			setVolumeControlStream(AudioManager.STREAM_MUSIC);

			RiverCrossingAI.setContext(this);

			this.loadSe();

			this.screen=(CoreScreen)findViewById(R.id.surfaceView);
			this.screen.setOnTouchListener(this);
			this.screen.setLoadEndRecieve(new ScreenLoadEndRecieve());

			this.objectFactory=new CoreObjectFactory(screen);
			this.textObjectFactory=new CoreTextObjectFactory(screen);

		    schedule.scheduleWithFixedDelay(this, 0, 1, TimeUnit.MILLISECONDS);

		    //メモリーの整理
		    objectFactory.deleteAll();
		    textObjectFactory.deleteAll();
		    RiverCrossingAI.getImagePool().cleanDatas();



	 }



	//更新処理
	@Override
	public void run() {

		if(screen.isInitEnd() && RiverCrossingAI.getSePlayer().isLoadEnd()){

			float difTime=System.currentTimeMillis()-time;
			time=System.currentTimeMillis();

			float deltaTime= (difTime/1000.0f);

			if(deltaTime>1){
				deltaTime=0.1f;
			}

			update(deltaTime);
			screen.checkCollision();
			screen.draw();	//描画関連
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		if(!RiverCrossingAI.isCanTouch()) return false;

		if(event.getAction()==MotionEvent.ACTION_UP){
			this.screen.checkTouchUp(event.getX(),event.getY());
		}else if(event.getAction()==MotionEvent.ACTION_DOWN){
			this.screen.checkTouchDown(event.getX(), event.getY());
		}

		this.touch(event);

		return false;
	}


	@Override
	protected void onResume() {
		super.onResume();


		if(schedule==null){
			schedule = new ScheduledThreadPoolExecutor(1);
			schedule.scheduleWithFixedDelay(this, 0, 1, TimeUnit.MILLISECONDS);
		}
		RiverCrossingAI.getBgmPlayer().play();
		this.loadSe();

		if(wakeLock!=null){
			wakeLock.acquire();
		}else{
			PowerManager pm = (PowerManager)getSystemService(POWER_SERVICE);
			wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "tag");
			wakeLock.acquire();
		}

	}

	@Override
	protected void onPause() {
		super.onPause();
		RiverCrossingAI.getImagePool().cleanDatas();
		RiverCrossingAI.getBgmPlayer().pause();
		RiverCrossingAI.getSePlayer().release();
		schedule.shutdown();
		schedule=null;

		wakeLock.release();
	}





	/**
	 * 戻るボタンの封印
	 */
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
	    if (event.getAction()==KeyEvent.ACTION_DOWN) {
	        switch (event.getKeyCode()) {
	        case KeyEvent.KEYCODE_BACK:
	            // ダイアログ表示など特定の処理を行いたい場合はここに記述
	            // 親クラスのdispatchKeyEvent()を呼び出さずにtrueを返す
	            return true;
	        }
	    }
	    return super.dispatchKeyEvent(event);
	}



}
