package com.xjd.wolfpuzzle;

import java.util.Random;
import sprite.BlockGroup;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class GameView extends SurfaceView implements SurfaceHolder.Callback,Runnable{
	
	Bitmap smallImage;
	Bitmap bigImage;
	Bitmap clockImage;
	Bitmap replayImage;
	Bitmap currentImg;
	BlockGroup bGroup;
	BlockGroup rGroup;
	SurfaceHolder holder;
	Canvas canvas;
	Paint paint;
	RectF smallRectF;
	RectF replyRectF;
	long startTime;
	int gameX=10,gameY=120;
	float eventX,eventY;
	float bigScale;
	int score=0;
	Random r;
	private Context mContext;
	
	public static boolean stop=true;
	public static final int GAMESTATE_READY=0;
	public static final int GAMESTATE_RUN=1;
	public static final int GAMESTATE_SHOW=2;
	public static final int GAMESTATE_REPLY=3;
	public static final int GAMESTATE_WIN=4;
	int gameState;
	public GameView(Context context) {
		super(context);
		mContext = context;
		// TODO Auto-generated constructor stub
		currentImg=BitmapFactory.decodeResource(context.getResources(), MyAdapter.gameImage[MyAdapter.imageIndex]);
		smallImage=Bitmap.createScaledBitmap(currentImg, 100, 100, true);
		smallRectF=new RectF(10, 10, 110, 110);
		replyRectF=new RectF(220, 60, 270, 110);
//		clockImage=BitmapFactory.decodeResource(context.getResources(), R.drawable.k);
//		replayImage=BitmapFactory.decodeResource(context.getResources(),R.drawable.up);

		bigScale=((GameActivity.screecW-20)/currentImg.getWidth());
		bigImage=Bitmap.createScaledBitmap(currentImg, (int)(GameActivity.screecW-20), (int)(currentImg.getHeight()*bigScale), true);
		bGroup=new BlockGroup(bigImage, MyAdapter.levelNum);
		rGroup=new BlockGroup(bigImage, MyAdapter.levelNum);
		gameState=GAMESTATE_READY;
		r=new Random();
		holder=this.getHolder();
		holder.addCallback(this);
		}
	
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (stop) {
			try {
				event();
				update();
				render();
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	String rfinal="图片打乱中.";
	
	int readyTime=1;
	int readyCount=0;
	int winCount=0;
	int replayCount;
	int replayCurrentStep;
	int[]replayStart;
	int[][]replaySteps;
	int replayState;
	private void update() {
		// TODO Auto-generated method stub
		switch (gameState) {
		
		case GAMESTATE_READY:
			if (readyCount<readyTime) {
				bGroup.flushBlocks(readyTime*100);	
				rfinal="图片打乱中.";
				for(int i=0;i<readyCount%3;i++){
					
					rfinal+=".";
				}
				readyCount++;
				
			}else {
				readyCount=0;
				startTime=System.currentTimeMillis();
				gameState=GAMESTATE_RUN;
				replayStart=bGroup.getmap();
			 }
		
			break;
		case  GAMESTATE_RUN:
			
			break;
		case GAMESTATE_SHOW:
			
			break;
		case GAMESTATE_REPLY:
			replayCount++;
			if (replayCount>1) {
//				if (replayCount%2==0 && replayCurrentStep<bGroup.steps.length) {
//					rGroup.doMove(bGroup.steps[replayCurrentStep][0], bGroup.steps[replayCurrentStep][1]);
//					replayCurrentStep++;
//				}else 
//					if (replayCurrentStep>=bGroup.steps.length)
					{
					if(replayState==GAMESTATE_WIN){
						gameState=GAMESTATE_WIN;
						score=(int) (System.currentTimeMillis()-startTime);						
					}else {
						gameState=GAMESTATE_RUN;
					}						
				}
			}
			break;
		case GAMESTATE_WIN:
			winCount++;
			
//		if (winCount>90) {
////				GameActivity.instance.gotoInput(score/1000);
//			    stop=false;	    
//			}
			break;		
		}
	}
	
		int eventType;
		public static final int EVENT_NOT=0;
		public static final int EVENT_DOWN=1;
		public static final int EVENT_UP=2;
	private void event() {
		// TODO Auto-generated method stub
		if (eventType==EVENT_NOT)
			return;
		if (eventType==EVENT_DOWN) {
			switch (gameState) {
			case GAMESTATE_RUN:
				if (bGroup.onChick(eventX-gameX,eventY-gameY)) {
					gameState=GAMESTATE_REPLY;
					replayCount=0;
					replayCurrentStep=0;
					rGroup.setmap(replayStart);
					replayState=GAMESTATE_WIN;
				}else if (smallRectF.contains(eventX, eventY)) {
					gameState=GAMESTATE_SHOW;
				}else if (replyRectF.contains(eventX, eventY)) {
					if (bGroup.steps==null) {
						break;
					}else{
					gameState=GAMESTATE_REPLY;
					replayCount=0;
					replayCurrentStep=0;
					rGroup.setmap(replayStart);
					replayState=GAMESTATE_RUN;}
				}
				break;

			case GAMESTATE_SHOW:
				gameState=GAMESTATE_RUN;
				break;
			case GAMESTATE_WIN:
			    stop=false;
			    mListener.onSuccess();
			}
		}
		eventType=EVENT_NOT;
		

	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if(event.getAction()==MotionEvent.ACTION_DOWN){
			eventType=EVENT_DOWN;
			eventX=event.getX();
			eventY=event.getY();
		}

		
		return super.onTouchEvent(event);
	}

	

	private void render() {
		// TODO Auto-generated method stub

	
		canvas=holder.lockCanvas();
		
		canvas.drawColor(Color.DKGRAY);
		
		
		switch (gameState) {
		case GAMESTATE_READY:
			
			renderReady();
			break;

		case GAMESTATE_RUN:
			renderRun();
			break;
		case GAMESTATE_SHOW:
			renderShow();
			break;
		case GAMESTATE_REPLY:
//			renderReply();
			break;
		case GAMESTATE_WIN:
			renderWin();
			break;
		}
		holder.unlockCanvasAndPost(canvas);
	}


	private void renderReady() {
		// TODO Auto-generated method stub
		
		paint =new Paint();
		paint.setColor(Color.YELLOW);
		paint.setTextSize(32);
		canvas.drawText(rfinal, 50, 100, paint);
		bGroup.paint(canvas, 10, 120, paint);
	}

	private void renderRun() {
		// TODO Auto-generated method stub
		paint=new Paint();
		canvas.drawBitmap(smallImage, 10,10, paint);
//		canvas.drawBitmap(clockImage, 220, 10, paint);
//		canvas.drawBitmap(replayImage, 220, 60, paint);
		bGroup.paint(canvas, 10, 120, paint);
		paint.setColor(Color.YELLOW);
		paint.setTextSize(40);
        canvas.drawText(getCurrentTime(), 270, 50, paint);
		
	}

	private void renderShow() {
		// TODO Auto-generated method stub
		canvas.drawBitmap(bigImage, 10, 10, paint);
	}

	private void renderReply() {
		// TODO Auto-generated method stub
		rGroup.paint(canvas, 10, 120, paint);
	}

	private void renderWin() {
		// TODO Auto-generated method stub
		canvas.drawBitmap(bigImage, 10, 10, paint);
		paint.setColor(Color.rgb(r.nextInt(256), r.nextInt(256), r.nextInt(256)));
		paint.setTextSize(58);
		canvas.drawText("你的成绩为："+ score/1000+ "秒。解锁下一关！！！", 100, GameActivity.screeH-150, paint);
		setMissionVer(mContext, "mission", MyAdapter.imageIndex+1);
	}
	private int getMissionVer(Context context,String key){
		int value = 0;
		SharedPreferences perf = context.getSharedPreferences("mission", 1);
		value = perf.getInt(key, 0);
		return value;
	}
	private void setMissionVer(Context context,String key,int value){
		SharedPreferences perf = context.getSharedPreferences("mission", 1);
		Editor editor = perf.edit();
		editor.putInt(key, value);
		editor.commit();
	}
	

	private String getCurrentTime() {
		// TODO Auto-generated method stub
		int seconds=(int) (System.currentTimeMillis()-startTime)/1000;
		int second=seconds%60;
		int min=( seconds/60)%60;
		int hour=seconds/3600;
		String time=(hour<10?"0"+hour:hour)+":"+(min<10?"0"+min:min)+":"+(second<10?"0"+second:second);
		return time;
	}

	@Override
	public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
		// TODO Auto-generated method stub		
	}

	@Override
	public void surfaceCreated(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		Thread thread=new Thread(this);
		thread.start();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder arg0) {
		// TODO Auto-generated method stub
		stop=false;
	}
	public interface OnWinListener {

		public void onSuccess(); 

	}

	private OnWinListener mListener;

	public void setOnWinListener(OnWinListener listener) {
		mListener = listener;
	}
}
