using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Imaging;
using Nlgp1.Common;
using System.Configuration;

namespace Nlgp1.StageEditor.Controls {
	public partial class MotionImageCreaterForm : Form {

		private int previewIndex = 0;

		public MotionImageCreaterForm() {
			InitializeComponent();
			saveButton.Enabled = false;
			imageColumn.ValuesAreIcons = false;
			imageColumn.ImageLayout = DataGridViewImageCellLayout.Zoom;

			foreach( var item in Enum.GetValues( typeof( MotionChipType ) ) ) {
				string typeName = ( (MotionChipType)item ).ToString();
				int index = defineList.Rows.Add();
				defineList[0 , index].Value = Utility.EnumLabelAttribute.GetLabel( ( (MotionChipType)item ) );
				typeColumn.Items.Add( defineList[0 , index].Value );
			}
		}

		private void chipFolderSelect_Click( object sender , EventArgs e ) {
			if( chipFolderSelectDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {
				foreach( var path in Directory.GetFiles( chipFolderSelectDialog.SelectedPath , "*.png" ) ) {
					int index = chipImageList.Rows.Add();
					string name = Path.GetFileNameWithoutExtension( path );
					chipImageList.Rows[index].Cells[0].Value = new Bitmap( path );
					chipImageList.Rows[index].Cells[2].Value = name;
					// ファイル名から動的に種別を選択する
					int lastLen = 0;
					foreach( var item in Enum.GetValues( typeof( MotionChipType ) ) ) {
						string typeName = ( (MotionChipType)item ).ToString();
						if( lastLen < typeName.Length && name.ToUpper().Contains( typeName.ToUpper() ) ) {
							lastLen = typeName.Length;
							chipImageList.Rows[index].Cells[1].Value = Utility.EnumLabelAttribute.GetLabel( ( (MotionChipType)item ) );
						}
					}
				}
				saveButton.Enabled = true;
			}
		}
		private void defineLoad_Click( object sender , EventArgs e ) {
			if( defineFileOpen.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {
				foreach( var line in File.ReadAllLines( defineFileOpen.FileName ) ) {
					if( string.IsNullOrEmpty( line.Trim() ) )
						continue;
					string[] cells = line.Split( ',' );
					if( cells.Length < 4 )
						continue;

					string name  = cells[0].Trim();
					string typeName = null;
					foreach( var item in Enum.GetValues( typeof( MotionChipType ) ) ) {
						if( ( (MotionChipType)item ).ToString() == name ) {
							typeName = Utility.EnumLabelAttribute.GetLabel( ( (MotionChipType)item ) );
							break;
						}
					}
					if( typeName == null )
						continue;
					foreach( DataGridViewRow row in defineList.Rows ) {
						if( typeName == row.Cells[0].Value as string ) {
							row.Cells[1].Value = Utility.TryParse<int>( cells[3].Trim() );
							row.Cells[2].Value = Utility.TryParse<bool>( cells[4].Trim() );
							defineList.UpdateCellValue( 1 , row.Index );
							defineList.UpdateCellValue( 2 , row.Index );
						}
					}

				}
			}
		}
		private void saveButton_Click( object sender , EventArgs e ) {
			if( chipSetSave.ShowDialog() == System.Windows.Forms.DialogResult.OK ) {
				CreateChipSetFile( chipSetSave.FileName );
			}
		}

		#region 並び替え
		private void chipDown_Click( object sender , EventArgs e ) {
			if( chipImageList.SelectedRows.Count == 0 || chipImageList.SelectedRows[0].Index == chipImageList.Rows.Count - 1 )
				return;

			int index = chipImageList.SelectedRows[0].Index + 2;
			chipImageList.Rows.Insert( index , 1 );
			for( int i = 0 ; chipImageList.SelectedRows[0].Cells.Count > i ; i++ ) {
				chipImageList.Rows[index].Cells[i].Value = chipImageList.SelectedRows[0].Cells[i].Value;
			}
			chipImageList.Rows.RemoveAt( chipImageList.SelectedRows[0].Index );
			chipImageList.Rows[index - 1].Selected = true;
			if( index - 4 <= 0 ) {
				chipImageList.FirstDisplayedScrollingRowIndex = 0;
			} else {
				chipImageList.FirstDisplayedScrollingRowIndex = index - 4;
			}
		}
		private void chipUp_Click( object sender , EventArgs e ) {
			if( chipImageList.SelectedRows.Count == 0 || chipImageList.SelectedRows[0].Index == 0 )
				return;

			int index = chipImageList.SelectedRows[0].Index - 1;
			chipImageList.Rows.Insert( index , 1 );
			for( int i = 0 ; chipImageList.SelectedRows[0].Cells.Count > i ; i++ ) {
				chipImageList.Rows[index].Cells[i].Value = chipImageList.SelectedRows[0].Cells[i].Value;
			}
			chipImageList.Rows.RemoveAt( chipImageList.SelectedRows[0].Index );
			chipImageList.Rows[index].Selected = true;
			if( index - 4 <= 0 ) {
				chipImageList.FirstDisplayedScrollingRowIndex = 0;
			} else {
				chipImageList.FirstDisplayedScrollingRowIndex = index - 4;
			}
		}
		#endregion

		/// <summary>
		/// 複数の画像からチップセットファイルを生成する
		/// </summary>
		/// <param name="saveFilePath">保存ファイル名</param>
		public void CreateChipSetFile( string saveFilePath ) {
			if( chipImageList.Rows.Count == 0 )
				return;
			Image img = chipImageList[0 , 0].Value as Image;
			int width = img.Width;
			int height = img.Height;

			Dictionary<MotionChipType,int> indexStarts = new Dictionary<MotionChipType , int>();
			Dictionary<MotionChipType,int> indexEnds   = new Dictionary<MotionChipType , int>();

			using( Image tempImage = new Bitmap( chipImageList.Rows.Count * width , height ) ) {
				int x = 0;
				using( Graphics tempGraphic = Graphics.FromImage( tempImage ) ) {

					StringBuilder define = new StringBuilder();

					foreach( var mType in Enum.GetValues( typeof( MotionChipType ) ).Cast<MotionChipType>() ) {
						indexStarts.Add( mType , -1 );
						indexEnds.Add( mType , -1 );
						foreach( DataGridViewRow temp in chipImageList.Rows ) {
							if( temp.Cells[1].Value as string == Utility.EnumLabelAttribute.GetLabel( mType ) ) {
								tempGraphic.DrawImage( temp.Cells[0].Value as Image , x * width , 0 , width , height );
								if( indexStarts[mType] == -1 )
									indexStarts[mType] = x;
								indexEnds[mType] = x;
								x++;
							}
						}
						// define生成
						if( indexStarts[mType] == -1 )
							continue;
						foreach( DataGridViewRow row in defineList.Rows ) {
							if( row.Cells[0].Value as string == Utility.EnumLabelAttribute.GetLabel( mType ) ) {
								define.AppendFormat( "{0},{1},{2},{3},{4}" , mType.ToString() , indexStarts[mType] , indexEnds[mType] ,
									row.Cells[1].Value == null ? 0 : row.Cells[1].Value , row.Cells[2].Value == null ? "FALSE" : row.Cells[2].Value );
								define.AppendLine();
							}
						}
					}
					tempImage.Save( saveFilePath , ImageFormat.Png );
					File.WriteAllText( Path.Combine( Path.GetDirectoryName( saveFilePath ) , string.Format( "{0}.def" , Path.GetFileNameWithoutExtension( saveFilePath ) ) ) , define.ToString() );

				}

			}

		}

		// プレビュー
		private void preview_Tick( object sender , EventArgs e ) {
			if( defineList.SelectedRows.Count > 0 ) {
				for( int i = previewIndex ; chipImageList.Rows.Count > i ; i++ ) {
					if( chipImageList.Rows[i].Cells[1].Value as string == defineList.SelectedRows[0].Cells[0].Value as string ) {
						preview.Image = chipImageList[0 , i].Value as Image;
						previewIndex = ++i;
						return;
					}
				}
			}
			previewIndex = 0;
		}


	}


}
