/////////////////////////////////////////////////////////////////////////////
//  Copyright(c)2008, Qizhi Zhang. http://www.moorwind.com. 
//
//  Licensed under the Apache License, Version 2.0 (the "License");
//  you may not use this file except in compliance with the License.
//  You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
//  Unless required by applicable law or agreed to in writing, software
//  distributed under the License is distributed on an "AS IS" BASIS,
//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//  See the License for the specific language governing permissions and
//  limitations under the License.
/////////////////////////////////////////////////////////////////////////////
package {
    import cn.myspace.MyspaceService;
    import cn.myspace.data.Friends;
    import cn.myspace.events.MyspaceServiceEvent;
    import cn.myspace.utils.Page;
    
    import com.moorwind.spacehammer.data.BitmapParam;
    import com.moorwind.spacehammer.data.Position;
    import com.moorwind.spacehammer.events.ImageLoaderEvent;
    import com.moorwind.spacehammer.events.WindowEvent;
    import com.moorwind.spacehammer.props.Avatar;
    import com.moorwind.spacehammer.props.Hammer;
    import com.moorwind.spacehammer.props.Helper;
    import com.moorwind.spacehammer.props.MoreGameButton;
    import com.moorwind.spacehammer.props.MovieLoader;
    import com.moorwind.spacehammer.props.ShowHelpButton;
    import com.moorwind.spacehammer.props.StartGameButton;
    import com.moorwind.spacehammer.props.Window;
    import com.moorwind.spacehammer.utils.ImageLoaderList;
    
    import flash.display.MovieClip;
    import flash.display.SimpleButton;
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;
    import flash.events.TimerEvent;
    import flash.net.URLRequest;
    import flash.net.navigateToURL;
    import flash.text.TextField;
    import flash.utils.Timer;

    public class SpaceHammer extends MovieClip
    {
        private const MDP_URL    :String = "http://apps.myspace.cn/";
        private const AUTHOR_URL:String = "http://www.moorwind.com/";
        private const API_KEY    :String = "http://www.myspace.cn/1307696709";
        private const API_SECRET:String = "7e7c5279f19445dbb451fb253398e2d8";
        
        private const INTERVAL    :uint = 800;
        private const POSITION    :Array/* Position */ = [
                                            new Position(65.3, 26.5), new Position(207, 26.5), new Position(336.6, 26.5),
                                              new Position(64.3, 134.5), new Position(207.5, 134.5), new Position(336.1, 134.5),
                                              new Position(63.9, 242.5), new Position(207.5, 242.5), new Position(336.6, 242.5),
                                          ];
        
        private var windows        :Sprite;                                  
        private var list        :ImageLoaderList;
        private var timer        :Timer;
        private var totalScore    :Array/* BitmapParam */ = [];
        private var prevLoader    :MovieLoader = new MovieLoader();
        private var hammer        :Hammer = new Hammer();
        private var helper        :Helper = new Helper();
        private var startGame    :StartGameButton = new StartGameButton();
        private var showHelp    :ShowHelpButton = new ShowHelpButton();
        private var moreGame    :MoreGameButton = new MoreGameButton();
        
        private var userid        :uint = 1307025489;
        private var service        :MyspaceService;
        private var friends        :Friends;
                
        //private var importBTN    :SimpleButton;
        //private var importTXT    :TextField;
        private var authorSite    :SimpleButton;
        private var score        :TextField;
        
        public function SpaceHammer()
        {
            super();                    
            
            if(this.loaderInfo.parameters["userid"])
                this.userid = uint(this.loaderInfo.parameters["userid"]) ;
            
            this.prevLoader.x = 148.6;
            this.prevLoader.y = 100.3;
            this.addChild(this.prevLoader);
            
            this.initData();
            this.stop();
            
            this.addEventListener(Event.RENDER, this.onRender);
            authorSite.addEventListener(MouseEvent.CLICK, this.onAuthor);
            this.stage.invalidate();
        }
        
        private function initData():void
        {
            this.service = new MyspaceService(this.userid, this.API_KEY, this.API_SECRET);
            this.service.addEventListener(MyspaceServiceEvent.USERS_GET_FRIENDS, this.onGetFriends);
            this.service.user.getFriends(new Page("1", "80"));
            
        }
        
        private function onGetFriends(e:MyspaceServiceEvent):void
        {
            this.friends = e.data as Friends;
            var percent:Number = friends.list.length > 30 ? friends.list.length / 2 : 1;
            this.list = new ImageLoaderList(friends.list, percent);
            this.list.addEventListener(ImageLoaderEvent.FLAG_COMPLETE, this.onFlagLoaded);
            this.list.addEventListener(ImageLoaderEvent.FLAG_PROGRESS, this.onFlogProgress);
            this.list.start();
        }
        
        private function onFlogProgress(e:ImageLoaderEvent):void
        {
            var percent:Number = uint(e.data) / 80;
            this.prevLoader.progress = percent;
        }
                
        private function onFlagLoaded(e:Event):void
        {
            this.stage.invalidate();            
            this.removeChild(this.prevLoader);            
            this.gotoAndStop("opinion");            
        }
        
        private function initHammer():void
        {
            this.windows = new Sprite();
            this.addChild(this.windows);
            this.addChild(this.hammer);            
            this.hammer.startHammer();
        }
        
        private function onRender(e:Event):void
        {            
            if(this.currentLabel == "opinion")
            {
                this.addOpinionButton();
                startGame.addEventListener(MouseEvent.CLICK, this.onStartGame);
                showHelp.addEventListener(MouseEvent.CLICK, this.onHelp);
                moreGame.addEventListener(MouseEvent.CLICK, this.onMoreGame);
            }
            
            if(this.currentLabel == "game")
            {
                this.removeOpinionButton();
                this.initHammer();
            }
            
            if(this.currentLabel == "over")
            {
                //reGame.addEventListener(MouseEvent.CLICK, this.onRestartGame);
                score.text = this.totalScore.length + " δΈͺ";
            }
        }
        
        private function addOpinionButton():void
        {
            this.addChild(this.startGame);
            this.addChild(this.showHelp);
            this.addChild(this.moreGame);
        }
        
        private function removeOpinionButton():void
        {
            try
            {
                this.removeChild(this.startGame);
                this.removeChild(this.showHelp);
                this.removeChild(this.moreGame);
            }
            catch(e:Error)
            {
                
            }
        }
                
        private function onStartGame(e:MouseEvent = null):void
        {
            this.stage.invalidate();
            this.gotoAndStop("game");
            this.timer = new Timer(this.INTERVAL);
            this.timer.addEventListener(TimerEvent.TIMER, this.showAvatar);
            this.timer.start();
        }
        
        private function onRestartGame(e:MouseEvent = null):void
        {
            this.list.start();
        }
        
        private function showAvatar(e:TimerEvent = null):void
        {
            if(this.list.list.length <= 0)
            {
                this.timer.stop();
                this.timer = new Timer(this.INTERVAL);
                this.timer.addEventListener(TimerEvent.TIMER, this.onGameOver);
                this.timer.start();
                return;
            }
            var window:Window = this.creatWindow();
            var point:Position = this.POSITION[this.getRandomPosition()];
            window.x = point.x;
            window.y = point.y;
            window.addEventListener(WindowEvent.WINDOW_CLOSE, this.removeWindow);
            this.windows.addChild(window);
            window.startAvatar();
        }
        
        private function onGameOver(e:TimerEvent = null):void
        {
            this.timer.stop();
            this.hammer.stopHammer();
            this.removeChild(this.hammer);
            this.stage.invalidate();
            this.gotoAndStop("over");            
        }
                
        private function creatWindow():Window
        {
            var param:BitmapParam = this.list.list.pop();
            var avatar:Avatar = new Avatar(param, this.hammer);
            return new Window(avatar);
        }
        
        private function removeWindow(e:WindowEvent):void
        {
            var window:Window = e.target as Window;
            try
            {
                this.windows.removeChild(window);
            }
            catch(e:Error)
            {
                //trace(e.message);
            }
            
            if(e.isClicked)
            {
                this.totalScore.push(window.bitmapParam);
            }
        }
        
        private function getRandomPosition():uint
        {
            return int(Math.random()*this.POSITION.length)
        }
        
        private function onHelp(e:MouseEvent):void
        {
            this.addChild(this.helper);
            this.helper.helpBack.addEventListener(MouseEvent.CLICK, this.onCloseHelp);
        }
        
        private function onCloseHelp(e:MouseEvent):void
        {
            this.removeChild(this.helper);
        }
            
        private function onMoreGame(e:MouseEvent):void
        {
            navigateToURL(new URLRequest(this.MDP_URL));
        }    
        
        private function onAuthor(e:MouseEvent):void
        {
            navigateToURL(new URLRequest(this.AUTHOR_URL));
        }    

    }
}