<?xml version="1.0" encoding="ISO-8859-1"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:cti_control="CTI.technique.controls.*" xmlns="*" 
	creationComplete="onCreationComplete()"
	styleName="CTIView"
	width="100%" height="100%"
	paddingTop="0" paddingBottom="0" paddingRight="0" paddingLeft="0"
	creationPolicy="all" mouseOver="showEventHandle()">
	<mx:Script>
        <![CDATA[   
		
			import flash.events.*;
			import flash.utils.Timer;
			import mx.collections.ArrayCollection;
			import mx.containers.TitleWindow;
			import flash.net.URLRequest;
			import flash.net.FileReference;
			import mx.events.DropdownEvent;
		
			import mx.utils.StringUtil;
			import CTI.technique.CTI_Utilitaires;
			
		
			import mx.controls.Alert;
			import mx.rpc.events.ResultEvent;
			import mx.rpc.events.FaultEvent;
			import mx.rpc.remoting.RemoteObject;
			import flash.utils.ByteArray;
			
			private var _ro:RemoteObject;

			[Embed(source="../../base/swf/CTI/images/32/ibus.png")]
            public static var info_icon_class:Class;
		
			[Bindable]
			public var title:String = "Bilan Social";
			
			[Bindable]
			public var bsLabel:String = "<b><font size=\"16\">Bilan Social</font></b>";
			
			[Bindable]
			public var bsSubLabel:String = "<i>Défini par l'<font color=\"#0000FF\"><u><a href=\"http://www.legifrance.gouv.fr/affichCodeArticle.do?idArticle=LEGIARTI000022266069&cidTexte=LEGITEXT000006072050\" target=\"_blank\" >article R. 2323-17 du code du travail</a></u></font>.</i>";
			
			[Bindable]
			public var hasHelp:Boolean = false;
			
			[Bindable]
			public var imports_list:ArrayCollection = new ArrayCollection();
			
			[Bindable]
			public var annees:Array = new Array(2015, 2014, 2013, 2012, 2011);
			
			[Bindable]
			public var entites:Array = new Array();
			
			[Bindable]
			public var diagnoseList:Array = new Array();
			
			public var entitiesAll:Array = new Array();

			public var _enabled:Boolean = true;
			
			private var downloadURL:URLRequest;
			private var fileRef:FileReference;
			
			private var filename:String;

			public var _disabledMessage:String = "Le bilan social nécessite une visite de validation de CTI Santé pour démarrer cette fonctionnalité.";

			public function showEventHandle():void {
				if (!this._enabled) {
					Alert.show(this._disabledMessage, "Message de CTI Santé", Alert.OK, this, null, info_icon_class);
					application.closeCurrentWindow();
				}
			}

			public function onCreationComplete():void {
				var _secureAMF:Boolean = this.url.indexOf('https') >= 0 ? true : false;
				_ro = application.ctiRemoteObjectProvider.getRemoteObject("rh", "CtiRhBilanSocialService", _secureAMF);
				
				isBsEnabled();
			}

			private function isBsEnabled():void {
				_ro.addEventListener(ResultEvent.RESULT, handleBsEnabledResult);
				_ro.addEventListener(FaultEvent.FAULT, handleBsEnabledFault);
				_ro.isBsEnabled();
            }
			
			private function handleBsEnabledResult(event:ResultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleBsEnabledResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleBsEnabledFault);
				_enabled = event.result as Boolean;

				if (_enabled) {
					getEntities();
				} else {
					Alert.show(this._disabledMessage, "Message de CTI Santé", Alert.OK, this, null, info_icon_class);
					application.closeCurrentWindow();
				}
			}

			private function handleBsEnabledFault(event:FaultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleBsEnabledResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleBsEnabledFault);
				_ro.disconnect();
				Alert.show(this._disabledMessage, "Message de CTI Santé", Alert.OK, this, null, info_icon_class);
				application.closeCurrentWindow();
			}
			
			private function getEntities():void {
				_ro.addEventListener(ResultEvent.RESULT, handleEntitiesResult);
				_ro.addEventListener(FaultEvent.FAULT, handleEntitiesFault);
				_ro.getEntities();
            }
			
			private function handleEntitiesResult(event:ResultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleEntitiesResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleEntitiesFault);
				entitiesAll = event.result as Array;
				for each(var o:Object in entitiesAll) {
					entites.push(o.texte);
				}
				if (entitiesAll.length > 0) {
					cbEntity.selectedIndex = 0;
					diagnose();
				} else {
					Alert.show("Impossible de lister les entreprises/établissements.", "Bilan Social.");
				}
			}

			private function handleEntitiesFault(event:FaultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleEntitiesResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleEntitiesFault);
				_ro.disconnect();
				Alert.show("Impossible de lister les entreprises/établissements.", "Bilan Social.");
			}
			
			private function generer():void {
				btnTelecharger.enabled = false;
				
				btnGenerer.label = "Génération en cours...";
				btnGenerer.enabled = false;
				cbYear.enabled = false;
				cbEntity.enabled = false;
				
				filename = "BilanSocial_"+cbYear.selectedItem+"_"+entitiesAll[cbEntity.selectedIndex].code+".xlsx";
				
				_ro.addEventListener(ResultEvent.RESULT, handleDataListResult);
				_ro.addEventListener(FaultEvent.FAULT, handleDataListFault);
				_ro.generateExcel(cbYear.selectedItem, filename, entitiesAll[cbEntity.selectedIndex].ent_id, entitiesAll[cbEntity.selectedIndex].ets_id);
            }
			
			private function handleDataListResult(event:ResultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleDataListResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleDataListFault);
				var res:String = event.result as String;
				
				if (res == "diagnose") {
					diagnose();
				} else {
					checkIfRealError();
				}
			}

			private function handleDataListFault(event:FaultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleDataListResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleDataListFault);
				_ro.disconnect();
				
				/*
				Etant donné que PHP 5.2.5 fait planter Apache mais que malgré tout le fichier est bien
				généré, on considère qu'on a une chance de le récupérer si amfPHP est en erreur.
				*/
				checkIfRealError();
			}
			
			private function checkIfRealError():void {
				_ro.addEventListener(ResultEvent.RESULT, handleFgResult);
				_ro.addEventListener(FaultEvent.FAULT, handleFgFault);
				_ro.fileGenerated(filename);
			}
			
			private function handleFgResult(event:ResultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleFgResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleFgFault);
				var res:Boolean = event.result as Boolean;
				
				btnGenerer.label = "Générer";
				btnGenerer.enabled = true;
				cbYear.enabled = true;
				cbEntity.enabled = true;
					
				if(res) {
					btnTelecharger.enabled = true;
				} else {
					Alert.show("Impossible de générer le Bilan Social. Fichier non généré.", "Bilan Social.");
				}
			}

			private function handleFgFault(event:FaultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleFgResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleFgFault);
				_ro.disconnect();
				
				btnGenerer.label = "Générer";
				btnGenerer.enabled = true;
				cbYear.enabled = true;
				cbEntity.enabled = true;
				
				Alert.show("Impossible de générer le Bilan Social.", "Bilan Social.");
			}
			
			private function telecharger():void {
				var appUrl:String = Application.application.url.replace("CTI.swf", "temp/");
				downloadURL = new URLRequest();
				downloadURL.url = appUrl + filename;
				fileRef = new FileReference();
				configureListeners(fileRef);
				fileRef.download(downloadURL, filename);
			}
			
			private function configureListeners(dispatcher:IEventDispatcher):void {
				dispatcher.addEventListener(Event.CANCEL, cancelHandler);
				dispatcher.addEventListener(Event.COMPLETE, completeHandler);
				dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
				dispatcher.addEventListener(Event.OPEN, openHandler);
				dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
				dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
				dispatcher.addEventListener(Event.SELECT, selectHandler);
			}
			
			private function cancelHandler(event:Event):void {
				trace("cancelHandler: " + event);
			}

			private function completeHandler(event:Event):void {
				trace("completeHandler: " + event);
				Alert.show(filename + " téléchargé.", "Bilan Social.");
			}

			private function ioErrorHandler(event:IOErrorEvent):void {
				trace("ioErrorHandler: " + event);
				Alert.show("Impossible de télécharger le Bilan Social.\nVous n'êtes peut-être pas connecté au réseau ou vous essayer d'écraser un fichier actuellement ouvert sur votre ordinateur.", "Bilan Social.");
			}

			private function openHandler(event:Event):void {
				trace("openHandler: " + event);
			}

			private function progressHandler(event:ProgressEvent):void {
				var file:FileReference = FileReference(event.target);
				trace("progressHandler name=" + file.name + " bytesLoaded=" + event.bytesLoaded + " bytesTotal=" + event.bytesTotal);
			}

			private function securityErrorHandler(event:SecurityErrorEvent):void {
				trace("securityErrorHandler: " + event);
				Alert.show("Impossible de télécharger le Bilan Social. Mettez à jour votre plugin Flash Player du navigateur.", "Bilan Social.");
			}

			private function selectHandler(event:Event):void {
				var file:FileReference = FileReference(event.target);
				trace("selectHandler: name=" + file.name + " URL=" + downloadURL.url);
			}
			
			private function diagnose():void {
				btnVerifier.label = "Vérification en cours...";
				btnVerifier.enabled = false;
				
				_ro.addEventListener(ResultEvent.RESULT, handleDiagnoseResult);
				_ro.addEventListener(FaultEvent.FAULT, handleDiagnoseFault);
				_ro.diagnose();
			}
			
			private function handleDiagnoseResult(event:ResultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleDiagnoseResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleDiagnoseFault);
				var res:Array = event.result as Array;
				
				diagnoseList = res;
				
				if (diagnoseList.length > 0){
					excelVBox.visible = false;
					excelVBox.includeInLayout = false;
				} else {
					excelVBox.visible = true;
					excelVBox.includeInLayout = true;
				}
				
				btnVerifier.label = "Relancer la vérification";
				btnVerifier.enabled = true;
				
				btnGenerer.label = "Générer";
				btnGenerer.enabled = true;
			}

			private function handleDiagnoseFault(event:FaultEvent):void {
				_ro.removeEventListener(ResultEvent.RESULT, handleDiagnoseResult);
				_ro.removeEventListener(FaultEvent.FAULT, handleDiagnoseFault);
				_ro.disconnect();
				
				Alert.show("Impossible de vérifier les pré-requis pour la génération du Bilan Social.", "Bilan Social.");
				
				btnVerifier.label = "Relancer la vérification";
				btnVerifier.enabled = true;
			}
			
        ]]>
    </mx:Script>
	<cti_control:CTIViewTitle id="GUI_titleBar" label="{title}" width="100%" height="25" />
	<mx:VBox width="100%" height="60%" horizontalAlign="center" verticalAlign="middle">
		<mx:Form borderStyle="solid" backgroundColor="0xdbdbdb" cornerRadius="4">
			<mx:VBox horizontalAlign="center" width="100%">
				<mx:Label htmlText="{bsLabel}"/>
				<mx:Label htmlText="{bsSubLabel}"/>
			</mx:VBox>
			<mx:HBox horizontalAlign="center" width="100%">
				<mx:Image source="@Embed('../../base/swf/CTI/images/96/application-vnd.ms-excel.png')"/>
			</mx:HBox>
			<mx:Spacer height="10" />
			
			<mx:VBox id="diagnoseVBox" width="100%" height="100%" visible="{diagnoseList.length > 0}" includeInLayout="{diagnoseList.length > 0}" horizontalAlign="center" verticalAlign="middle">
				<mx:Label htmlText="&lt;b&gt;Veuillez corriger les erreurs suivantes :&lt;/b&gt;"/>
				<mx:Repeater id="diagnoseRpt" dataProvider="{diagnoseList}">
					<mx:HBox horizontalAlign="center" width="100%">
						<mx:Image source="@Embed('../../base/swf/CTI/images/16/dialog-error.png')"/>
						<mx:Label htmlText="{diagnoseRpt.currentItem.error_message.toString()}" />
					</mx:HBox>
				</mx:Repeater>
				<mx:Spacer height="10" />
				<mx:Button id="btnVerifier" label="Relancer la vérification" icon="@Embed('../../base/swf/CTI/images/24/dialog-ok.png')" width="100%" height="30" click="diagnose()"/>
			</mx:VBox>
			
			<mx:VBox id="excelVBox" width="100%" height="100%" visible="false" includeInLayout="false" horizontalAlign="center" verticalAlign="middle">
				<mx:FormItem label="Année">
					<mx:ComboBox id="cbYear" dataProvider="{annees}" />
				</mx:FormItem>
				<mx:FormItem label="Entité" >
					<mx:ComboBox id="cbEntity" dataProvider="{entites}" />
				</mx:FormItem>
				<mx:Button id="btnGenerer" label="Générer" icon="@Embed('../../base/swf/CTI/images/24/system-run.png')" width="100%" height="30" click="generer()" />
				<mx:Button id="btnTelecharger" label="Télécharger" icon="@Embed('../../base/swf/CTI/images/24/document-save-as.png')" width="100%" height="30" click="telecharger()" enabled="false"/>
			</mx:VBox>
		</mx:Form>
	</mx:VBox>
</mx:Application>
