
package robot {
	
	import flash.display.Sprite;
	import flash.display.NativeWindow;
	import flash.events.*;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	import flash.text.TextFormat;
	import flash.net.navigateToURL;
	import flash.utils.Timer;		
	import flash.media.SoundChannel;
	
	
	import flash.net.URLVariables;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.events.IOErrorEvent;
	
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.filesystem.File;
	
	public class Robot extends Sprite {
		
		private var myRequest:URLRequest;
		private var myLoader:URLLoader;
		private var myTextField:TextField;
		private var tf1:TextField;
		private var myXML:XML;
		private var increaseValue:Number;
		private var myFileStream:FileStream;
		private var myOtherXML:XML;
		private var textFormat:TextFormat;
		private var myWeatherXML:XML;
		private var myWeatherLoader:URLLoader;
		private var myTimer:Timer = new Timer (10000);
		private var myRobotDance:robotDance = new robotDance();
		private var myDanceBeat:danceBeat = new danceBeat();
		private var myBoing:boing = new boing();
		private var myElectro:Electro = new Electro();
		private var myChannel:SoundChannel;
		private var myFile:File;
		private var xmlData:String;
		
		
		public function Robot() {
			
			myRobot.gotoAndStop(1);
			myTimer.start();
			createTextField();
			
			myTimer.addEventListener(TimerEvent.TIMER, makeRobotDance);
			
			myRobot.addEventListener(MouseEvent.MOUSE_DOWN, dragWindow);
			
			myCloseBtn.addEventListener(MouseEvent.CLICK, closeWindow);
			
			myAddBtn.buttonMode = true;
			myAddBtn.addEventListener(MouseEvent.CLICK, addTextBox);
			
			myWeatherBtn.buttonMode = true;
			myWeatherBtn.addEventListener(MouseEvent.CLICK, checkWeather);
			
			myQuote.buttonMode = true;
			myQuote.addEventListener(MouseEvent.CLICK, getQuote);
			
			//checks to see if robot.xml file exists or not
			myFile = File.documentsDirectory;
			myFile = myFile.resolvePath("robot.xml");
			
			//if it doesn't exist, it pulls xml from the application
			if (!myFile.exists) {
				
				myLoader = new URLLoader(); // this is the loader that will receive the XML
				myRequest = new URLRequest();
				myRequest.url= 'robot.xml';
				myRequest.method=URLRequestMethod.POST;
				myLoader.load(myRequest);
				myLoader.addEventListener(Event.COMPLETE, showText);
				trace ("file does not exist");
			}
			
			else {
				
				myFileStream = new FileStream();

				myFileStream.open(myFile, FileMode.READ);
				xmlData = myFileStream.readUTFBytes(myFileStream.bytesAvailable);
				myFileStream.addEventListener(Event.CLOSE, writeFile);
				myFileStream.close();
				trace ("file exists");
				//trace (xmlData);
				myOtherXML = new XML(xmlData);
				//trace ("myOtherXML " + myOtherXML);
				increaseValue = myOtherXML.saying.children().length()-1;
				trace("p is " + increaseValue);
				myTextField.appendText(myOtherXML.saying.(@number == 1));
				
			}
			
		}
		
		private function writeFile(e:Event):void {
			
			//updates file in users directory when they submit sayings using the add expression feature
			
			myFileStream = new FileStream();
			
            myFileStream.openAsync(myFile, FileMode.UPDATE);
			myFileStream.writeUTFBytes(myOtherXML);
          
		   	myFileStream.addEventListener(Event.CLOSE, fileWrittenComplete);
			myFileStream.close();
			
		}
		
		private function fileWrittenComplete(e:Event) {
		
			trace ("robot has been written to the file system.");
		}
			
		private function createTextField() { 
			
			//creates text field
			myTextField = new TextField();
			myTextField.width = 250;
			myTextField.height = 100;
			myTextField.x = myBubble.x;
			myTextField.y = myBubble.y;
			myTextField.wordWrap = true;
			textFormat = new TextFormat();
			textFormat.font = "Futura";
			myTextField.defaultTextFormat = textFormat;
			addChild(myTextField);
		
		}
		
			//loads initial text into speech bubble
			private function showText(e:Event) {
			
			try {
				// the data comes into the e.target.data property
				myOtherXML = new XML(e.target.data);
				myTextField.appendText(myOtherXML.saying.(@number == 1));
				increaseValue = myOtherXML.saying.children().length()-1;
				//trace ("myOtherXML from Show text is " +  myOtherXML);
				writeNewFile();
				
			}
			catch (e:TypeError)
			{
				myTextField.text = "XML error";
			}
			
			
		}
		
		private function writeNewFile() {
			
			//writes new XML file in user's documents directory if one doesn't already exist
			
			myFileStream = new FileStream();
			
			if (!myFile.exists)
            {
                myFileStream.openAsync(myFile, FileMode.WRITE);
				myFileStream.writeUTFBytes(myOtherXML);
            }
            else
            {
                myFileStream.openAsync(myFile, FileMode.UPDATE);
				myFileStream.writeUTFBytes(myOtherXML);
           }
           
		   	myFileStream.addEventListener(Event.CLOSE, fileWrittenComplete);
			myFileStream.close();
			trace ("hi from writeNewFile");
			
		}
		
		//adds text field for user input
		private function addTextBox(e:MouseEvent):void {
			
			tf1 = new TextField();
			tf1.width = 200;
			tf1.height = 50;
			tf1.border = true;
			tf1.y = 160;
			tf1.x = 80;
			tf1.background = true;
			tf1.backgroundColor = 0xFFFFFF;
			tf1.type = TextFieldType.INPUT;
			tf1.defaultTextFormat = textFormat;
			addChild(tf1);
			myButton.buttonMode = true;
			myButton.addEventListener(MouseEvent.CLICK, addXml);
			removeChild(myAddBtn);
			
		}
			
		//writes user input to xml file
		private function addXml(e:MouseEvent):void {
			increaseValue++;
			var roboto:String = "saying"; 
			var attributename:String = "number"; 
			var attributevalue:Number = increaseValue; 
			var content:String = tf1.text; 
			var x:XML = <{roboto} {attributename}={attributevalue}>{content}</{roboto}>; 
			myOtherXML = myOtherXML.appendChild(x);
			//trace (myOtherXML);
			
			
			myTextField.text = "";
			myTextField.appendText(myOtherXML.saying.(@number==increaseValue));
			myFileStream.openAsync(myFile, FileMode.UPDATE);
			myFileStream.writeUTFBytes(myOtherXML);
          
           
		   	myFileStream.addEventListener(Event.CLOSE, fileWrittenComplete);
			myFileStream.close();
			removeChild(tf1);
			addChild(myAddBtn);
			
			
		}
		
		//loads weather from rss
		private function checkWeather(e:MouseEvent):void {
			myWeatherXML = new XML();
			var XML_URL:String = "http://xml.weather.yahoo.com/forecastrss?p=CAXX0504&u=f";
			var myXMLURL:URLRequest = new URLRequest(XML_URL);
			myWeatherLoader = new URLLoader(myXMLURL);
			myWeatherLoader.addEventListener("complete", weatherLoaded);
			
		}
		
		//displays weather info
		private function weatherLoaded(e:Event):void {
			
			myWeatherXML = XML(myWeatherLoader.data);
			trace ("data loaded");
			myTextField.htmlText = myWeatherXML.channel.item.description;
			myTextField.x = 155;
			myTextField.y = 3;
			
		}
		
		//loads quote from rss
		private function getQuote(e:MouseEvent):void {
			myWeatherXML = new XML();
			var XML_URL:String = "http://www.arcamax.com/quotes/channelfeed";
			var myXMLURL:URLRequest = new URLRequest(XML_URL);
			myWeatherLoader = new URLLoader(myXMLURL);
			myWeatherLoader.addEventListener("complete", quoteLoaded);
			myChannel = myBoing.play();
			
		}
		//displays quote
		private function quoteLoaded(e:Event):void {
			
			myWeatherXML = XML(myWeatherLoader.data);
			trace ("data loaded");
			myTextField.htmlText = myWeatherXML.channel.item[5].description;
			myTextField.x = myBubble.x;
			myTextField.y = 40;
			
		}
		
		//changes text field and loads robotDance movie clip based on timer event and random number
		private function makeRobotDance(e:TimerEvent):void {
			
			myRobot.gotoAndStop(1);
			
			var i:Number = (Math.floor(Math.random()*6));
			//trace (i);
			if (i == 0) {
				myRobot.visible = false;
				addChild(myRobotDance);
				myChannel = myDanceBeat.play();
				myRobotDance.x = myRobot.x;
				myRobotDance.y = myRobot.y;
				myRobotDance.addEventListener(MouseEvent.MOUSE_OVER, stopDance);
				myChannel.addEventListener(Event.SOUND_COMPLETE, noMusic);
				myTextField.x = myBubble.x;
				myTextField.y = myBubble.y;
				myTextField.text = "";
				myTextField.appendText("DANCE PARTY!!!");
				
			}
			if (i > 0) {
				myTextField.x = myBubble.x;
				myTextField.y = myBubble.y;
				myTextField.text = "";
				var j:Number = (Math.floor(Math.random()*increaseValue));
				myTextField.appendText(myOtherXML.saying.(@number == j));
				myChannel = myElectro.play(3000);
				
			}
			if (i == 3 || i == 6) {
				myRobot.play();
				
			}
			
		}
		//removes robotDance movie clip
		private function stopDance(e:MouseEvent):void {
			
			myRobotDance.removeEventListener(MouseEvent.MOUSE_OVER, stopDance);
			removeChild(myRobotDance);
			myChannel.stop();
			myRobot.visible = true;
		}
		//stops robotDance when sound clip ends
		private function noMusic(e:Event):void {
			myChannel.removeEventListener(Event.SOUND_COMPLETE, noMusic);
			removeChild(myRobotDance);
			myRobot.visible = true;
		}
		
		//allows user to drag window around desktop
		private function dragWindow(e:MouseEvent):void {
			trace("drag window");
			stage.nativeWindow.startMove();
		}
		
		//closes application
		private function closeWindow(e:MouseEvent):void {
			trace("close window");
			stage.nativeWindow.close();
		}
		
		
	}
}
		