package com.example.super_duckhunt;

import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;
 
public class main extends Activity  {
	int Xpos,Ypos,pressX=0, pressY=0,screenWidth,screenHeight;
	int birdFrame=0, birdDirectionX = 1, birdDirectionY = 1, birdSpeedX = 10, birdSpeedY = 10;	
	int birdMinX=0, birdMinY =0, birdMaxX, birdMaxY;
	int drawBullet = 0, drawBirdHit=0, deadBirdDropSpeed = 3;
	public static int points=0;
	int totalBulletsReamining = 20;
	boolean birdAlive = true;
	public long mLastMove;
	MediaPlayer bgmusic;
	public RefreshHandler mRedrawHandler = new RefreshHandler();
	Toast  msg;
	Gender ob;
	//Make this global and load once, do not load every time the View is refreshed or else it slows.
	Bitmap newbg, resizedBg, bulletHole, birdHit, birdDead, bullet;   Bitmap[] bird = new Bitmap[3];
	Runnable runnableBG,runnableGun,runnableScream,runnableQuack;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);        
        setContentView(new ballView(this));   
        //setContentView(R.layout.main);   
              // this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        int orientation = getResources().getConfiguration().orientation;
        if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
        	newbg   = BitmapFactory.decodeResource(getResources(), R.drawable.bglandscape);
        }
        else {
        	newbg   = BitmapFactory.decodeResource(getResources(), R.drawable.bg);       
        }
        
        birdHit   = BitmapFactory.decodeResource(getResources(), R.drawable.birdhit);
        birdDead   = BitmapFactory.decodeResource(getResources(), R.drawable.bird0);
        bulletHole   = BitmapFactory.decodeResource(getResources(), R.drawable.smallhole);
        bullet = BitmapFactory.decodeResource(getResources(), R.drawable.bullet);
   	 
 	 	bird[0] =BitmapFactory.decodeResource(getResources(), R.drawable.bird1);
        bird[1] = BitmapFactory.decodeResource(getResources(), R.drawable.bird2);
        bird[2] = BitmapFactory.decodeResource(getResources(), R.drawable.bird3);  	
      
	    //Screensize
	    DisplayMetrics displaymetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        screenWidth = displaymetrics.widthPixels;
        screenHeight = displaymetrics.heightPixels;
        
        birdMaxX = screenWidth ;
        birdMaxY = screenHeight;
        
        Xpos = rand (0, screenWidth);
        Ypos = rand (0, screenHeight);
        
      ///Resize newBg
		float scaleWidth = ((float) screenWidth) / newbg.getWidth();
		float scaleHeight = ((float) screenHeight) / newbg.getHeight();

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		resizedBg = Bitmap.createBitmap(newbg, 0, 0, newbg.getWidth(), newbg.getHeight(), matrix, false);
        ///End Resize
        
        //Start Background Music
       runnableBG = new Runnable() {
		public void run() {
	    //Put this in a separate thread to speed up.
			MediaPlayer[] bgmusics = new MediaPlayer[4];
			bgmusics[0] = MediaPlayer.create(main.this, R.raw.bg1);
			bgmusics[1] = MediaPlayer.create(main.this, R.raw.bg2);
			bgmusics[2] = MediaPlayer.create(main.this, R.raw.bg3);
			bgmusics[3] = MediaPlayer.create(main.this, R.raw.bg4);
			        
			bgmusic = bgmusics[rand(0,3)];
		    
		   // bgmusic = MediaPlayer.create(main.this, R.raw.tik);
		    bgmusic.setLooping(true);
		    bgmusic.start();
		}	};
		runnableBG.run();
	
		//End Background Music
		
        
    }
   /*
    public boolean onKeyDown( int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_DOWN:
			//X = 0;		
			finish();
			break;	
		}			 
		 return true;
	
	} */
	public void update()   
    {	 
		  long now = System.currentTimeMillis();
          if (now - mLastMove > 100) {
            	setContentView(new ballView(this));   
                mLastMove = now;
            }
      mRedrawHandler.wait2(100);
    }
	public static int rand(int from, int to)
	{
		int r = 0;		
		r = from + (int)(Math.random()*(1+to-from));		
		return r;
	}
	class ballView extends View {
		 
		Canvas tempCanvas;
	    public ballView(Context context)
	    {
	    	super(context);
	    }
	    
	    
	    @Override
        public boolean onTouchEvent(MotionEvent event) {
		 
		pressX = (int) event.getX();
		pressY = (int) event.getY();
		
		int action = event.getAction();
		
		if (action==MotionEvent.ACTION_DOWN){
	
		checkClash(pressX,pressY);
		drawBullet = 1;
		totalBulletsReamining--;
		  if(totalBulletsReamining==0){
			  Bundle got=getIntent().getExtras();
			  String gt=got.getString("key");
	    	   Intent i=new Intent("android.intent.action.AFTER");
	    	   i.putExtra("hg",gt);
	    	   startActivity(i);
	       }
		/////////// start gun sound
		runnableGun = new Runnable() {
		public void run() {
	    //Put this in a separate thread to speed up.
	    MediaPlayer mp = MediaPlayer.create(main.this, R.raw.gun);
        mp.start();
			}};
			runnableGun.run();
		////////End gun sound
		}
		
		// Toast msg = Toast.makeText(better.this, "Key Pressed", Toast.LENGTH_SHORT);						
		/// msg.show();
		return true;
	    }
	    public void checkClash( int pressX , int pressY  )
		{
			int XDiff = Xpos-pressX;if(XDiff<0) XDiff*=-1;
			int YDiff = Ypos-pressY;if(YDiff<0) YDiff*=-1;
			
			if ( XDiff < 20 && YDiff <20 ) //Assume bird is 40x40
			  {				 
				birdAlive = false;
				drawBirdHit = 2;
				msg = Toast.makeText(main.this, "Good", Toast.LENGTH_SHORT);						
				msg.show();	
				//Bird Scream 
		        runnableScream = new Runnable() {
				public void run() {
			    //Put this in a separate thread to speed up.
					MediaPlayer[] scream = new MediaPlayer[3];
				    scream[0] = MediaPlayer.create(main.this, R.raw.scream1);
				    scream[1] = MediaPlayer.create(main.this, R.raw.scream2);
				    scream[2] = MediaPlayer.create(main.this, R.raw.scream3);
		        
				    scream[rand(0,2)].start();
				}	};
				runnableScream.run();
				//End Bird Scream
			  }
		}
		@Override
	    public void onDraw(Canvas canvas) {
			if(birdAlive==true)
				Xpos=Xpos+birdSpeedX*birdDirectionX;
	    	 if(Xpos>birdMaxX)
	    	 {
	    		 birdDirectionX = -1;
	    		 birdSpeedX = rand (10,30);
	    		 
	    		 birdMinX = rand (0,screenWidth/2-10);
	    		 birdMaxX = rand (screenWidth/2,screenWidth);
	    	 }
	    	 if(Xpos<birdMinX)
	    	 {
	    		 birdDirectionX = +1;
	    		 birdSpeedX = rand (10,30);
	    		 
	    		 birdMinX = rand (0,screenWidth/2-10);
	    		 birdMaxX = rand (screenWidth/2,screenWidth);
	    	 }
	    	
			if(birdAlive==true)
			{
				Ypos=Ypos+birdSpeedY*birdDirectionY;
		    	 if(Ypos>birdMaxY)
		    	 {
		    		 birdDirectionY = -1;
		    		 birdSpeedX = rand (10,30);
		    		 birdMinY = rand (0,screenHeight/2-10);
		    		 birdMaxY = rand (screenHeight/2,screenHeight);
		    	 }
		    	 if(Ypos<birdMinY)
		    	 {
		    		 birdDirectionY = +1;
		    		 birdSpeedX = rand (10,30);
		    		 birdMinY = rand (0,screenHeight/2-10);
		    		 birdMaxY = rand (screenHeight/2,screenHeight);
			    	 }
			}
			
			if(birdAlive==false)
			{
				Ypos=Ypos+deadBirdDropSpeed;
				deadBirdDropSpeed*=1.4;
				if(Ypos > 420)
				{
					//Restart Game, Increase Points
					birdAlive = true;
					points++;
					deadBirdDropSpeed = 3;
					
					//Bird Quack
			        runnableQuack = new Runnable() {
					public void run() {
				    //Put this in a separate thread to speed up.
				    MediaPlayer mp2 = MediaPlayer.create(main.this, R.raw.duck);
			        mp2.start();
					}	};
					runnableQuack.run();
					//End Bird Quack
				}
			}
	      // Bitmap bg = BitmapFactory.decodeResource(getResources(), R.drawable.bg);   
	      

	       canvas.drawBitmap(resizedBg, 0, 0, null);
	      
	       if(drawBullet ==1)
	       {
	    	   canvas.drawBitmap(bulletHole, pressX-10, pressY-10, null);
	    	   drawBullet = 0;
	       }
	        //canvas.drawColor(Color.YELLOW);
	        //Draw Bird	    
	      if (birdAlive == true)
	      {
	       canvas.drawBitmap(bird[birdFrame], Xpos-bird[birdFrame].getWidth()/2, Ypos-bird[birdFrame].getHeight()/2, null);
	        if(birdFrame==0)
	        	birdFrame =1;
	        else
	        	if(birdFrame==1)
	        		birdFrame = 2;
	        	else
	        		birdFrame = 0;
	      }
	      else
	      {
	    	  if(drawBirdHit==0)
	    		    canvas.drawBitmap(birdDead, Xpos-birdDead.getWidth()/2, Ypos-birdDead.getHeight()/2, null); 
	    	  else
	    	  {
	    		    canvas.drawBitmap(birdHit, Xpos-birdHit.getWidth()/2, Ypos-birdHit.getHeight()/2, null); 
	    		    drawBirdHit--;
	    	  } 
	      }
	        ///////////////////
	        Paint paint = new Paint();
		    paint.setColor(Color.BLACK);
	       
	        canvas.drawText("Coordinates = "+pressX+"-"+pressY+" ("+screenWidth+"-"+screenHeight+"), " +
	        		"Points = "+points, 50, screenHeight-5, paint);  
		   //////////////////
	        
	        /////////Bulllets
	        int extraSpace =10;
	        for (int i=0; i<totalBulletsReamining; i++)
	        {
	        	if(i%5==0)
	        		extraSpace += 12;
	         
	        	canvas.drawBitmap(bullet, i*8+extraSpace, 5, null); 	
	        }
	        ////////End Bullets
	        update();
	    }  
		
	} 

	class RefreshHandler extends Handler {
		 @Override
	        public void handleMessage(Message msg) {
	           main.this.update();	          
	        }
	        public void wait2(long delayMillis) {
	        	this.removeMessages(0);
	            sendMessageDelayed(obtainMessage(0), delayMillis);
	        }
	}

	///////////////////////////////////////////////////
	///////Start Menu
	private static final int MENU_ITEM_1 = Menu.FIRST + 1;
    private static final int MENU_ITEM_2 = Menu.FIRST + 2;
    private static final int MENU_ITEM_3 = Menu.FIRST + 3;

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
	{
    	
	    menu.add(Menu.NONE, MENU_ITEM_1, Menu.NONE,"Stop Music").setIcon(R.drawable.mute);
	 
	    menu.add(Menu.NONE, MENU_ITEM_2, Menu.NONE,
	    "Start Music").setIcon(R.drawable.sound);
	
	    menu.add(Menu.NONE, MENU_ITEM_3, Menu.NONE,
	    "Exit").setIcon(R.drawable.exit);
	
	    return (super.onCreateOptionsMenu(menu));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item)
	{
    switch (item.getItemId())
		{
		case MENU_ITEM_1:
			bgmusic.pause();			 
            break;
        case MENU_ITEM_2:
        	bgmusic.start();
        	break;
    case MENU_ITEM_3:
    		bgmusic.stop();
            //Join threads
    		finish();                
    }
    return (super.onOptionsItemSelected(item));
	    } 
	///////End Menu
	///////////////////////////////////////////////////
    
    @Override
    protected void onPause() {
        super.onPause();
        bgmusic.stop();
        // Another activity is taking focus (this activity is about to be "paused").
    }
    @Override
    protected void onStop() {
        super.onStop();
        bgmusic.stop();
        // The activity is no longer visible (it is now "stopped")
    }
}





