package activities;

import java.io.IOException;

import com.heyzap.sdk.HeyzapLib;

import org.anddev.andengine.audio.music.Music;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;

import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;

import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.ui.activity.BaseGameActivity;
import org.anddev.andengine.util.Debug;

import android.content.Intent;
import android.widget.Toast;


public class Menu extends BaseGameActivity {
        // ===========================================================
        // Constants
        // ===========================================================

        private static final int CAMERA_WIDTH = 800;
        private static final int CAMERA_HEIGHT = 480;

        // ===========================================================
        // Fields
        // ===========================================================

        private Camera mCamera;
        
        // Textures for storing the buttons and icons
        private Texture mButtonTexture;
        private Texture mLevelTexture;
        
        // Texture regions for button and icon sprite handling
        private TextureRegion mPlayTextureRegion;
        private TextureRegion mOptionsTextureRegion;
        private TextureRegion mCreditsTextureRegion;
        private TextureRegion mCloseTextureRegion;
        private TextureRegion mSoundOnTextureRegion;
        private TextureRegion mSoundOffTextureRegion;
        private TextureRegion mHeyZapTextureRegion;
        
        private TextureRegion mBackTextureRegion;
        private TextureRegion mPlayLevel1Texture;
        private TextureRegion mPlayLevel2Texture;
        private TextureRegion mPlayLevel3Texture;
        
        // Textures and regions for the backgrounds
        private Texture mBackgroundTexture;
        private Texture mCreditScreenTexture;
    	private TextureRegion mBackgroundTextureRegion;
    	private TextureRegion mCreditScreenTextureRegion;
    	
    	private static Music mMusic;
    	private static boolean isMusicOn; // Boolean to handle music between Menu and Game
    
    	// Sprite declarations for the interface
    	private Sprite soundOnButton , soundOffButton , backButton, closeButton , Level1Button, Level2Button
    	, Level3Button, playButton, optionsButton ,creditsButton, heyZapButton, creditScreenButton;
    	
    	
    	private Scene scene;
    	
    	private static Sound mButtonSound;
    	
    
    	

        // ===========================================================
        // Constructors
        // ===========================================================

        // ===========================================================
        // Getter & Setter
        // ===========================================================

        // ===========================================================
        // Methods for/from SuperClass/Interfaces
        // ===========================================================

        @Override
        public Engine onLoadEngine() {                
                this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
                return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera).setNeedsMusic(true).setNeedsSound(true));
        }

        @Override
        public void onLoadResources() {  	
        	
        	
        	
        	try {
    			mMusic = MusicFactory.createMusicFromAsset(this.mEngine.getMusicManager(), this, "mfx/menumusic.mp3");
    			
    			isMusicOn = true;
    		} catch (final IOException e) {
    			Debug.e("Error", e);
    		}
    		
    		
        	
        	
    		SoundFactory.setAssetBasePath("sfx/");
    		try {
    			Menu.mButtonSound = SoundFactory.createSoundFromAsset(this.mEngine.getSoundManager(), this, "beep-23.wav");
    		} catch (final IOException e) {
    			Debug.e("Error", e);
    		}
    		
    		//The next section creates from the assets all the textures used in the interface.
        		
    		 this.mLevelTexture = new Texture(1024, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
    	        
    	        this.mBackTextureRegion = TextureRegionFactory.createFromAsset(this.mLevelTexture, this, "gfx/levelMenuButtons/back.png", 0, 0);
    	        this.mPlayLevel1Texture = TextureRegionFactory.createFromAsset(this.mLevelTexture, this, "gfx/levelMenuButtons/level1.png",  64, 0);
    	        this.mPlayLevel2Texture = TextureRegionFactory.createFromAsset(this.mLevelTexture, this, "gfx/levelMenuButtons/level2.png",  264, 0);
    	        this.mPlayLevel3Texture = TextureRegionFactory.createFromAsset(this.mLevelTexture, this, "gfx/levelMenuButtons/level3.png",  464, 0);
    	                
        	
        	
        	
        	
                this.mButtonTexture = new Texture(1024, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
                
                this.mCloseTextureRegion = TextureRegionFactory.createFromAsset(this.mButtonTexture, this, "gfx/MenuButtons/cerrar.png", 0, 0);
                this.mPlayTextureRegion = TextureRegionFactory.createFromAsset(this.mButtonTexture, this, "gfx/MenuButtons/play.png", 64 , 0);
                this.mOptionsTextureRegion = TextureRegionFactory.createFromAsset(this.mButtonTexture, this, "gfx/MenuButtons/options.png", 384 ,0 );
                this.mCreditsTextureRegion = TextureRegionFactory.createFromAsset(this.mButtonTexture, this, "gfx/MenuButtons/credits.png", 614 ,0);
                this.mSoundOnTextureRegion = TextureRegionFactory.createFromAsset(this.mButtonTexture, this, "gfx/MenuButtons/sonidoon.png", 850 ,0);
                this.mSoundOffTextureRegion = TextureRegionFactory.createFromAsset(this.mButtonTexture, this, "gfx/MenuButtons/sonidooff.png",916 , 0);
                
                this.mCreditScreenTexture = new Texture(1024,512,TextureOptions.DEFAULT);
                this.mCreditScreenTextureRegion = TextureRegionFactory.createFromAsset(this.mCreditScreenTexture, this, "gfx/backgrounds/creditscreen.png",0,0);
                
                this.mBackgroundTexture = new Texture(1024, 512, TextureOptions.DEFAULT);
        		this.mBackgroundTextureRegion = TextureRegionFactory.createFromAsset(this.mBackgroundTexture, this, "gfx/backgrounds/menuBackground.png", 0, 0);
                this.mHeyZapTextureRegion = TextureRegionFactory.createFromAsset(this.mBackgroundTexture, this, "gfx/MenuButtons/heyzap_button_hdpi.png",800 , 100);


                this.mEngine.getTextureManager().loadTextures(this.mBackgroundTexture, this.mButtonTexture, this.mLevelTexture,this.mCreditScreenTexture);
        }

        @Override
        public Scene onLoadScene() {
                this.mEngine.registerUpdateHandler(new FPSLogger());

                scene = new Scene(2); // New scene to show with 2 layers (top for buttons and bottom for background)
                scene.setBackgroundEnabled(false);                
                
                // Adding background to the bottom layer
        		scene.getBottomLayer().addEntity(new Sprite(0, 0, this.mBackgroundTextureRegion));
        		
        		//The following structures are the definition of the Sprites for each button and
        		//also how should they react when touched in the screen
        		
        		backButton = new Sprite (700,30,this.mBackTextureRegion) {
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					Menu.playButtonSound();  
        					
        					//All these operations are required since we will be swapping 
        					//the level selection screen to the main menu screen.
        					
        					scene.getTopLayer().removeEntity(backButton);
        					scene.getTopLayer().removeEntity(Level1Button);
        					scene.getTopLayer().removeEntity(Level2Button);
        					scene.getTopLayer().removeEntity(Level3Button);
        					
        					
        					scene.unregisterTouchArea(backButton);
        					scene.unregisterTouchArea(Level1Button);
        					scene.unregisterTouchArea(Level2Button);
        					scene.unregisterTouchArea(Level3Button);
        					
        					
        					scene.getTopLayer().addEntity(closeButton);
        	        		scene.getTopLayer().addEntity(playButton);
        	        		scene.getTopLayer().addEntity(optionsButton);
        	        		scene.getTopLayer().addEntity(creditsButton);
        	        		
        	        	
        	        		scene.registerTouchArea(playButton);
        	        		scene.registerTouchArea(closeButton);        	
        	        		scene.registerTouchArea(optionsButton);
        	        		scene.registerTouchArea(creditsButton);
        	        		;
        				}
                            return true;
                    }
        			
        		};
        		Level1Button = new Sprite (50,50,this.mPlayLevel1Texture){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					Toast.makeText(Menu.this, "Loading level 1...", Toast.LENGTH_SHORT).show();
        					Menu.playButtonSound();
        					
        										
        					NewLevel.setMapName("Level1.tmx");	//We set the name map to be parsed				
        					
        					Menu.this.startActivity(new Intent(Menu.this,NewLevel.class)); // Game Level launcher   
        				}
        				return true;
                    }
        			
        		};
        		
        		Level2Button = new Sprite (50,200,this.mPlayLevel2Texture){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					Toast.makeText(Menu.this, "Loading level 2...", Toast.LENGTH_SHORT).show();
        					Menu.playButtonSound();
        										
        					NewLevel.setMapName("Level2.tmx");
        										
        					
        					Menu.this.startActivity(new Intent(Menu.this,NewLevel.class));    
        				}
        				return true;
                    }
        			
        		};
        		
        		Level3Button = new Sprite (50,350,this.mPlayLevel3Texture){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					Toast.makeText(Menu.this, "Loading level 3...", Toast.LENGTH_SHORT).show();
        					//Toast.makeText(Menu.this, "Work in progress...", Toast.LENGTH_SHORT).show();
        					Menu.playButtonSound();
        					
        					NewLevel.setMapName("Level3.tmx");
        					
        					Menu.this.startActivity(new Intent(Menu.this,NewLevel.class));    
        				}
        				return true;
                    }
        			
        		};
        		
        		
        		
        		heyZapButton = new Sprite (570, 380 , this.mHeyZapTextureRegion){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					mButtonSound.play();
        					HeyzapLib.checkin(Menu.this);
        				}
                            return true;
                    }
        			
        		};
        		
        		
        		closeButton = new Sprite (700,30,this.mCloseTextureRegion) {
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					mButtonSound.play();
        					finish();
        				}
                            return true;
                    }
        			
        		};
        		playButton = new Sprite (470,270,this.mPlayTextureRegion){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					//Toast.makeText(Menu.this, "Loading level...", Toast.LENGTH_SHORT).show();
        					//Menu.this.mMusic.stop();
        					mButtonSound.play();
        					scene.getTopLayer().removeEntity(optionsButton);
        					scene.getTopLayer().removeEntity(creditsButton);
        					scene.getTopLayer().removeEntity(playButton);
        					scene.getTopLayer().removeEntity(closeButton);
        					
        					scene.unregisterTouchArea(optionsButton);
        					scene.unregisterTouchArea(creditsButton);
        					scene.unregisterTouchArea(playButton);
        					scene.unregisterTouchArea(closeButton);

        					
        					
        					scene.getTopLayer().addEntity(backButton);
        					scene.getTopLayer().addEntity(Level1Button);
        					scene.getTopLayer().addEntity(Level2Button);
        					scene.getTopLayer().addEntity(Level3Button);
        					
        					
        					scene.registerTouchArea(backButton);
        					scene.registerTouchArea(Level1Button);
        					scene.registerTouchArea(Level2Button);
        					scene.registerTouchArea(Level3Button);
        				}
        				return true;
                    }
        			
        		};
        		optionsButton = new Sprite (0,200,this.mOptionsTextureRegion){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					mButtonSound.play();
        					Toast.makeText(Menu.this, "Work in progress", Toast.LENGTH_SHORT).show();
        				}
                            return true;
                    }
        			
        		};
        		creditsButton = new Sprite(-3, 300, this.mCreditsTextureRegion){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					mButtonSound.play();
        					scene.getTopLayer().removeEntity(optionsButton);
        					scene.getTopLayer().removeEntity(creditsButton);
        					scene.getTopLayer().removeEntity(playButton);
        					scene.getTopLayer().removeEntity(closeButton);
        					scene.getTopLayer().removeEntity(heyZapButton);
        					
        					if(isMusicOn == true){
        						scene.getTopLayer().removeEntity(soundOnButton);
        						scene.unregisterTouchArea(soundOnButton);        						
        					}else{
        						scene.getTopLayer().removeEntity(soundOffButton);
        						scene.unregisterTouchArea(soundOffButton);  
        					}
        					
        					
        					
        					scene.unregisterTouchArea(optionsButton);
        					scene.unregisterTouchArea(creditsButton);
        					scene.unregisterTouchArea(playButton);
        					scene.unregisterTouchArea(closeButton);
        					scene.unregisterTouchArea(heyZapButton);
        					
        					scene.getTopLayer().addEntity(creditScreenButton);
        					scene.registerTouchArea(creditScreenButton);
        					
        				}
                            return true;
                            
                    }
        				
        			
        		};
        		
        		
        		creditScreenButton = new Sprite(0, 0, this.mCreditScreenTextureRegion){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					mButtonSound.play();
        					
        					scene.getTopLayer().removeEntity(creditScreenButton);
        					scene.unregisterTouchArea(creditScreenButton);
        					
        					scene.getTopLayer().addEntity(closeButton);
        	        		scene.getTopLayer().addEntity(playButton);
        	        		scene.getTopLayer().addEntity(optionsButton);
        	        		scene.getTopLayer().addEntity(creditsButton);
        	        		scene.getTopLayer().addEntity(heyZapButton);
        	        		
        	        	
        	        		
        	        		if(isMusicOn == true){
        						scene.getTopLayer().addEntity(soundOnButton);
        						scene.registerTouchArea(soundOnButton);        						
        					}else{
        						scene.getTopLayer().addEntity(soundOffButton);
        						scene.registerTouchArea(soundOffButton);  
        					}  
        	        		
        	        	
        	        		scene.registerTouchArea(playButton);
        	        		scene.registerTouchArea(closeButton);        	
        	        		scene.registerTouchArea(optionsButton);
        	        		scene.registerTouchArea(creditsButton);
        	        		scene.registerTouchArea(heyZapButton);
        					
        				}
                            return true;
                            
                    }
        				
        			
        		};
        		
        		 soundOffButton = new Sprite (30, 410, this.mSoundOffTextureRegion){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					mButtonSound.play();
        				Menu.mMusic.resume();
        				isMusicOn = true;
        				scene.unregisterTouchArea(soundOffButton);
    					scene.getTopLayer().removeEntity(soundOffButton);
    					scene.getTopLayer().addEntity(soundOnButton);
    					scene.registerTouchArea(soundOnButton);
        				}
                            return true;
                    }
        			
        		};
        		
        		soundOnButton = new Sprite (30 , 410 , this.mSoundOnTextureRegion){
        			@Override
                    public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final float pTouchAreaLocalX, final float pTouchAreaLocalY) {
        				if (pSceneTouchEvent.getAction() == TouchEvent.ACTION_DOWN){
        					mButtonSound.play();
        					mMusic.pause();
        					isMusicOn = false;
        					scene.unregisterTouchArea(soundOnButton);
        					scene.getTopLayer().removeEntity(soundOnButton);
        					scene.getTopLayer().addEntity(soundOffButton);
        					scene.registerTouchArea(soundOffButton);
        				}
                            return true;
                    }
        			
        		};
        		
        		
       
        		
        		scene.getTopLayer().addEntity(closeButton);
        		scene.getTopLayer().addEntity(playButton);
        		scene.getTopLayer().addEntity(optionsButton);
        		scene.getTopLayer().addEntity(creditsButton);
        		scene.getTopLayer().addEntity(soundOnButton);
        		scene.getTopLayer().addEntity(heyZapButton);
        		
        		
        		
        		scene.registerTouchArea(playButton);
        		scene.registerTouchArea(closeButton);        	
        		scene.registerTouchArea(soundOnButton);
        		scene.registerTouchArea(optionsButton);
        		scene.registerTouchArea(creditsButton);
        		scene.registerTouchArea(heyZapButton);
        		

                return scene;
        }

        @Override
        public void onLoadComplete() {
        	
        	mMusic.setLooping(true);
        	
        	mMusic.play();
        	// Heyzap game social network integration
        	
        	HeyzapLib.promptCheckin(Menu.this);
        }
        
       
        
       

        // ===========================================================
        // Methods
        // ===========================================================
        
        protected static void pauseMusic(){
        	
        	mMusic.pause();       
        	
        	
        }
        
        protected static void resumeMusic(){
        	
        	mMusic.resume();
        	
        }
        
        protected static boolean isMusicOn(){
        	
        	return isMusicOn;
        }
        
        protected static boolean isMusicPlaying(){
        	
        	return mMusic.isPlaying();
        }

        @Override
        // To prevent the music from playing out of window focus
        public void onWindowFocusChanged(boolean pHasWindowFocus) {
        	
            super.onWindowFocusChanged(pHasWindowFocus);
            
           if(isMusicOn()){ 
        	if(pHasWindowFocus == false)
        		mMusic.pause();
        	else 
        		mMusic.resume();     
        	}
        
        }
        
        protected static void playButtonSound(){
        	mButtonSound.play();
        }
        // ===========================================================
        // Inner and Anonymous Classes
        // ===========================================================
        
}