using System;
using System.Data;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Export;

namespace LLNet.GUI.FormBases
{
    public partial class frmGridToolbarBase : LLNet.GUI.FormBases.frmDataViewToolbarBase 
	{
		private DevExpress.XtraBars.BarButtonItem btnPrint;
		protected DevExpress.XtraPrinting.PrintingSystem printSystem;
		protected DevExpress.XtraPrinting.PrintableComponentLink printEngine;
		protected System.Windows.Forms.Panel pnGrid;
		public DevExpress.XtraGrid.GridControl dbGrid;
		protected DevExpress.XtraGrid.Views.Grid.GridView gridView1;
		protected DevExpress.XtraBars.Bar tblPrinting;
		private DevExpress.XtraBars.Bar bar1;
		private DevExpress.XtraBars.BarSubItem barSubItem1;
		private DevExpress.XtraBars.BarSubItem barSubItem2;
		private DevExpress.XtraBars.BarButtonItem barButtonItem1;
		private System.Windows.Forms.SaveFileDialog sf;
        private DevExpress.XtraBars.Docking.DockManager dockManager1;
        //protected LLNet.GUI.Bases.ctlStyles ctlStyles1;
        

		public frmGridToolbarBase()
		{
			// This call is required by the Windows Form Designer.
			InitializeComponent();
		}

		public virtual void FormatGridColumns()
		{
			this.dbGrid.Styles.AddReplace("CenterStyle", new DevExpress.Utils.ViewStyleEx("CenterStyle", "", "", true, false, false, DevExpress.Utils.HorzAlignment.Center, DevExpress.Utils.VertAlignment.Center, null, System.Drawing.SystemColors.Window, System.Drawing.SystemColors.WindowText, System.Drawing.Color.Empty, System.Drawing.Drawing2D.LinearGradientMode.Horizontal));
			this.dbGrid.Styles.AddReplace("RightStyle", new DevExpress.Utils.ViewStyleEx("CenterStyle", "", "", true, false, false, DevExpress.Utils.HorzAlignment.Far, DevExpress.Utils.VertAlignment.Center, null, System.Drawing.SystemColors.Window, System.Drawing.SystemColors.WindowText, System.Drawing.Color.Empty, System.Drawing.Drawing2D.LinearGradientMode.Horizontal));
			this.dbGrid.Styles.AddReplace("LeftStyle", new DevExpress.Utils.ViewStyleEx("CenterStyle", "", "", true, false, false, DevExpress.Utils.HorzAlignment.Near, DevExpress.Utils.VertAlignment.Center, null, System.Drawing.SystemColors.Window, System.Drawing.SystemColors.WindowText, System.Drawing.Color.Empty, System.Drawing.Drawing2D.LinearGradientMode.Horizontal));
			
			foreach (DevExpress.XtraGrid.Columns.GridColumn gCol in gridView1.Columns)
			{
				if ( gCol.UnboundType == DevExpress.Data.UnboundColumnType.Bound && gCol.DisplayFormat.FormatType != DevExpress.Utils.FormatType.Custom )
				{
					if (dataViewToolbar.Table.Columns[gCol.FieldName].DataType == typeof(System.DateTime))
					{
						gCol.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
					}
					else if (dataViewToolbar.Table.Columns[gCol.FieldName].DataType == typeof(System.Decimal))
					{
						gCol.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
						gCol.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric;
						gCol.DisplayFormat.FormatString = "#,###,##0.00";
					}
					else if (dataViewToolbar.Table.Columns[gCol.FieldName].DataType == typeof(System.Int64))
					{
						gCol.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
					}
					else
					{
						gCol.AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Near;
					}
				}				
			}
		}

		public override void Init(object[] pArgs)
		{
			
			Utils.QueryParams qParams = new LLNet.Utils.QueryParams();
			// Verifica que se envien argumentos al listado
			if (pArgs != null)
			{
				if (pArgs[0] is DataRowView)
				{
			
					// si el primer argumento es un DataRowView
					try
					{
						currentRow = pArgs[0] as DataRowView;
						DataRow[] drRow = new DataRow[] { currentRow.Row };

						// se genera un set de parametros en base a la llave primaria
			
						foreach ( DataColumn col in currentRow.Row.Table.PrimaryKey )
						{
							if (col.DataType == typeof(String))
								qParams.AddRecursiveConditionParam(Utils.QueryParams.PredefinedTags.DetailRelationTag,"AND",col.ColumnName,"=","'" + currentRow.Row[col.ColumnName,DataRowVersion.Original].ToString() + "'");
							else
								qParams.AddRecursiveConditionParam(Utils.QueryParams.PredefinedTags.DetailRelationTag,"AND",col.ColumnName,"=",currentRow.Row[col.ColumnName,DataRowVersion.Original].ToString());

						}

						// configuro el set de parametros para que lo maneje dbToolbar
						this.QueryParams = qParams;
					}
					catch (Exception ex)
					{
						GUI.CApp.EventLog.WriteLog(Utils.Types.ErrorTypes.MESSAGES,ex.Message);
					}
					base.Init (pArgs);

				}
				else if (pArgs[0] is Utils.QueryParams) //la construccion no es generica, sino que se conocen las columnas y valores de la llave primaria
				{
					qParams = (Utils.QueryParams)pArgs[0];
					this.QueryParams = qParams;
					base.Init (pArgs);				
				}
				else
				{
					base.Init(pArgs);
				}
			}
			else
			{
				base.Init (pArgs);
			}
			FormatGridColumns();
			try
			{
				object oldDs = dbGrid.DataSource;
				dbGrid.DataSource = null;
				dbGrid.DataSource = oldDs;
			}
			catch{}
			try
			{
				/*ctlStyles1.GridView = gridView1;
				ctlStyles1.Init(null);
				ctlStyles1.RefreshFormatConditions();*/
			}
			catch 
			{
				
			}

		}



		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		

	

		private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			PrintDocument();
		}

		protected virtual void PrintDocument()
		{
			
			DevExpress.XtraPrinting.PageHeaderArea headerArea;
			DevExpress.XtraPrinting.PageFooterArea footerArea;

			DevExpress.XtraPrinting.PageHeaderFooter header;

			headerArea = new DevExpress.XtraPrinting.PageHeaderArea();
			headerArea.Content.Add(this.Text.ToUpper());
			headerArea.Font = new Font("Arial",12,System.Drawing.FontStyle.Bold);
			headerArea.LineAlignment = DevExpress.XtraPrinting.BrickAlignment.Near;

			footerArea = new DevExpress.XtraPrinting.PageFooterArea();
			footerArea.LineAlignment = DevExpress.XtraPrinting.BrickAlignment.Far;
			footerArea.Content.Add("");
			footerArea.Content.Add("");
			footerArea.Content.Add("[Date Printed][Time Printed]");

			header = new DevExpress.XtraPrinting.PageHeaderFooter(headerArea,footerArea);
			printEngine.PageHeaderFooter = header;

			printEngine.CreateDocument();
			printEngine.ShowPreview();
		}

		public virtual void Export()
		{
			foreach(FieldInfo field in this.GetType().GetFields(BindingFlags.NonPublic|BindingFlags.Instance))
			{
				if ( field.FieldType.FullName.StartsWith("DevExpress") )
				{
					if (field.FieldType.IsSubclassOf(typeof(DevExpress.XtraGrid.Views.Base.BaseView)))
					{
						DevExpress.XtraGrid.Views.Base.BaseView vw = ((DevExpress.XtraGrid.Views.Base.BaseView)field.GetValue(this));
						if (vw.GridControl.Focused == true && vw == vw.GridControl.FocusedView )
						{
							sf.Filter = "Archivos de Excel(*.xls)|*.xls";
							if (sf.ShowDialog() == DialogResult.OK)
							{
								GridViewExportLink gvLink = vw.CreateExportLink(new DevExpress.XtraExport.ExportXlsProvider(sf.FileName)) as GridViewExportLink;
								if (gvLink != null)
								{
									gvLink.ExportAll = true;
									gvLink.ExpandAll = true;
									gvLink.ExportTo(true);
								}
								else
								{
									DevExpress.XtraEditors.XtraMessageBox.Show("No es Posible Exportar a Excel en este Tipo de Vista",this.Text,MessageBoxButtons.OK,MessageBoxIcon.Information);
								}
								
							}
						}
					}
				}
			}
		}


		private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
		{
			Export();
		}

	}
}