package cls.com.ils.common.component
{
	import commonLibrary.sharedComponent.ComboBoxEditor;
	
	import flash.display.DisplayObject;
	import flash.display.InteractiveObject;
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	import mx.controls.DataGrid;
	import mx.events.DataGridEvent;
	import mx.events.ListEvent;
	
	public class IlsDataGrid extends DataGrid implements IIlsControl
	{
		
		private var _lastSelectedIndex:int;
    	private var lastEditedItemPosition:*;

	    /**
	     *  Constructor.
	     */
		public function IlsDataGrid()
		{
			//TODO: implement function
			super();
			_lastSelectedIndex = -1;
			addEventListener(ListEvent.CHANGE,listChangeHandler);
		}

	    protected var footer:DataGridFooter;
	
		protected var footerHeight:int = 22;

		private function  listChangeHandler(event:ListEvent):void{
			_lastSelectedIndex = selectedIndex;
		}
		
	    //----------------------------------
	    //  footerEnabled
	    //----------------------------------
	
	    /**
	     *  @private
	     */
	    private var _footerEnabled:Boolean = false;
	
	    [Inspectable(defaultValue="true")]
	
	    /**
	     *  @default false
	     */
	    public function get footerEnabled():Boolean
	    {
	        return _footerEnabled;
	    }
	    
	    /**
	     *  @private
	     */
	    public function set footerEnabled(value:Boolean):void
	    {
	        _footerEnabled = value;
	    }

		override protected function createChildren():void
		{
	        super.createChildren();
	
			if (footerEnabled)
			{
		        if (!footer)
		        {
		            footer = new DataGridFooter();
		            footer.styleName = this;
		            addChild(footer);
		        }			
			}
		}
		
		override protected function adjustListContent(unscaledWidth:Number=-1, unscaledHeight:Number=-1):void
		{
			super.adjustListContent(unscaledWidth, unscaledHeight);
	
			if (footerEnabled)
			{
				listContent.setActualSize(listContent.width, listContent.height - footerHeight);
				footer.setActualSize(listContent.width, footerHeight);
				footer.move(listContent.x, listContent.y + listContent.height + 1);			
			}
		}
		
		override public function invalidateDisplayList():void
		{
			super.invalidateDisplayList();
			if (footerEnabled)
			{
				if (footer)
					footer.invalidateDisplayList();			
			}
		}

		override public function createItemEditor(colIndex:int, rowIndex:int):void
		{
			super.createItemEditor(colIndex,rowIndex);
	        if (itemEditorInstance)
	        {
		        // listen for keyStrokes on the itemEditorInstance (which lets the grid supervise for ESC/ENTER)
		        DisplayObject(itemEditorInstance).addEventListener(KeyboardEvent.KEY_DOWN, editorKeyDownHandler);			
	        }
		}
		
		override public function destroyItemEditor():void
		{			
	        if (itemEditorInstance)
	        {
	            DisplayObject(itemEditorInstance).removeEventListener(KeyboardEvent.KEY_DOWN, editorKeyDownHandler);
	        }
//				if(itemEditorInstance && itemEditorInstance is TextInputEditor){
//					var editor:TextInputEditor = itemEditorInstance as TextInputEditor;
//					//データ検証結果
//		            var resultEvent:ValidationResultEvent = editor.getValidator().validate();
//		            if (resultEvent.type != ValidationResultEvent.VALID){
//						super.destroyItemEditor();
//					}
//				}else{
//					super.destroyItemEditor();
//				}		    	
			super.destroyItemEditor();
		}
		
	    /**
	     *  @private
	     */
	    private function editorKeyDownHandler(event:KeyboardEvent):void
	    {
            //イベントの発生元のオブジェクトを取得して、InteractiveObjectにキャスト
            var interactiveObject :InteractiveObject = event.currentTarget as InteractiveObject;
            
            if(event.currentTarget is ComboBoxEditor){
            }else{
	            //下向き矢印キーに対するイベントの場合
	            if(event.keyCode == Keyboard.DOWN && !event.ctrlKey)
	            {
					if(rowValidate(event))
					{
		                //イベントの発生元のオブジェクトがInteractiveObjectの場合
		                if(event.currentTarget is InteractiveObject)
		                {
							findNextEnterItemRenderer(event);
		                }
	    			}
	            }else if(event.keyCode == Keyboard.UP && !event.ctrlKey){
	            //上向き矢印キーに対するイベントの場合
					if(rowValidate(event))
					{
		                //イベントの発生元のオブジェクトがInteractiveObjectの場合
		                if(event.currentTarget is InteractiveObject)
		                {
		                	event.shiftKey = true;
							findNextEnterItemRenderer(event);
		                }
					}
	            }
            }
	    }

		public function rowValidate(event:KeyboardEvent):Boolean
		{
			return true;
		}
		
//エディタが消えてしまうので、削除
//	    private function endEdit(reason:String):Boolean
//	    {
//	        // this happens if the renderer is removed asynchronously ususally with FDS
//	        if (!editedItemRenderer)
//	            return true;
//	
//			lastEditedItemPosition = {columnIndex: editedItemPosition.columnIndex, rowIndex: editedItemPosition.rowIndex};	        
//
//	        var dataGridEvent:DataGridEvent =
//	            new DataGridEvent(DataGridEvent.ITEM_EDIT_END, false, true);
//	            // ITEM_EDIT events are cancelable
//	        dataGridEvent.columnIndex = editedItemPosition.columnIndex;
//	        dataGridEvent.dataField = columns[editedItemPosition.columnIndex].dataField;
//	        dataGridEvent.rowIndex = editedItemPosition.rowIndex;
//	        dataGridEvent.itemRenderer = editedItemRenderer;
//	        dataGridEvent.reason = reason;
//	        dispatchEvent(dataGridEvent);
//	
//	        return !(dataGridEvent.isDefaultPrevented())
//	    }
//
//	    private function findNextEnterItemRenderer(event:KeyboardEvent):void
//	    {	
//	        var rowIndex:int = editedItemPosition.rowIndex;
//	        var columnIndex:int = editedItemPosition.columnIndex;
//	        // SHIFTキーで上段、下段を判断する (up or down)
//	        var newIndex:int = editedItemPosition.rowIndex +
//	                           (event.shiftKey ? -1 : 1);
//
//			if(itemEditorInstance && itemEditorInstance is TextInputEditor){
//				if(selectedItem){
//					var editor:TextInputEditor = itemEditorInstance as TextInputEditor;
//					selectedItem[columns[editedItemPosition.columnIndex].dataField]=editor.text;
//				}
//			}
//
//	        // 新規行が範囲内の場合のみ設定する、それ以外は現在行
//	        if (newIndex < collection.length && newIndex >= 0)
//	            rowIndex = newIndex;
//	
//	        var dataGridEvent:DataGridEvent =
//	            new DataGridEvent(DataGridEvent.ITEM_EDIT_END, false, true);
//	            // ITEM_EDIT events are cancelable
//	        dataGridEvent.columnIndex = editedItemPosition.columnIndex;
//	        dataGridEvent.dataField = columns[editedItemPosition.columnIndex].dataField;
//	        dataGridEvent.rowIndex = editedItemPosition.rowIndex;
//	        dataGridEvent.itemRenderer = editedItemRenderer;
//	        dataGridEvent.reason = DataGridEventReason.NEW_ROW;
//	        dispatchEvent(dataGridEvent);
//
//			this.editedItemPosition = {columnIndex: columnIndex, rowIndex: rowIndex};	        
//	    }

	    private function findNextEnterItemRenderer(event:KeyboardEvent):void
	    {	
			if(itemEditorInstance && itemEditorInstance is IlsTextInput){
				if(selectedItem){
					var editor:IlsTextInput = itemEditorInstance as IlsTextInput;
					selectedItem[columns[editedItemPosition.columnIndex].dataField]=editor.text;
				}
			}	        
//			if(itemEditorInstance && itemEditorInstance is TextInputEditor){
//				if(selectedItem){
//					var editor:TextInputEditor = itemEditorInstance as TextInputEditor;
//					selectedItem[columns[editedItemPosition.columnIndex].dataField]=editor.text;
//				}
//			}	        
	        var rowIndex:int = editedItemPosition.rowIndex;
	        var columnIndex:int = editedItemPosition.columnIndex;
	        
	        // SHIFTキーで上段、下段を判断する (up or down)
	        var newIndex:int = editedItemPosition.rowIndex +
	                           (event.shiftKey ? -1 : 1);
	        // 新規行が範囲内の場合のみ設定する、それ以外は現在行
	        if (newIndex < collection.length && newIndex >= 0)
	            rowIndex = newIndex;
	
	        // send event to create the new one
	        var dataGridEvent:DataGridEvent =
	            new DataGridEvent(DataGridEvent.ITEM_EDIT_BEGINNING, false, true);
	            // ITEM_EDIT events are cancelable
	        dataGridEvent.columnIndex = columnIndex;
	        dataGridEvent.dataField = columns[columnIndex].dataField;
	        dataGridEvent.rowIndex = rowIndex;
	        dispatchEvent(dataGridEvent);
	    }

		/**
		 *  項目を初期化する
		 * 
		 */		
		public function clearMe():void
		{
			this.dataProvider = null;
			this.lastSelectedIndex = -1;
		}
		
		/**
		 *  コントロールを入力不可にする
		 * @param isLock　True:ロックする、False:ロック解除
		 * 
		 */		
		public function lock(isLock:Boolean):void
		{
			this.enabled = !isLock;
		}
		
	    /**
	     *  The index in the data provider of the selected item.
	     * 
	     *  <p>The default value is -1 (no selected item).</p>
	     *
	     */
	    public function get lastSelectedIndex():int
	    {
	        return _lastSelectedIndex;
	    }
	
	    /**
	     *  @private
	     */
	    public function set lastSelectedIndex(value:int):void
	    {
            _lastSelectedIndex = value;
	    }

	}
}