using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows;
using System.Xml.Linq;
using C1.Silverlight.DataGrid;

namespace C1DataGrid_Demo2010
{
    public partial class Selection : System.Windows.Controls.UserControl
    {
        public Selection()
        {
            InitializeComponent();

            DataContext = Person.Generate(300);
        }

        public DataGridSelectionMode SelectionMode
        {
            get
            {
                return grid.SelectionMode;
            }
            set
            {
                grid.SelectionMode = value;
            }
        }

        public DataGridColumnHeaderClickAction ColumnHeaderClickAction
        {
            get
            {
                return grid.ColumnHeaderClickAction;
            }
            set
            {
                grid.ColumnHeaderClickAction = value;
            }
        }

        private XDocument GetExcelFile(bool generateColumnTitles, bool setRowHeight, bool setColumnWidth)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            string excelTemplateResourcestring = assembly.GetManifestResourceNames().First((resourceName) => resourceName.Contains(".Resources.ExcelTemplate.xml"));
            XDocument xml = XDocument.Load(assembly.GetManifestResourceStream(excelTemplateResourcestring));
            var table = (from element in xml.Descendants("{urn:schemas-microsoft-com:office:spreadsheet}Worksheet")
                        where element.Attribute("{urn:schemas-microsoft-com:office:spreadsheet}Name").Value == "Sheet1"
                         select element.Element("{urn:schemas-microsoft-com:office:spreadsheet}Table")).First();

            //table settings
            var orderedColumns = grid.Columns.OrderBy(column => column.DisplayIndex).ToList();
            table.SetAttributeValue("{urn:schemas-microsoft-com:office:spreadsheet}ExpandedColumnCount", orderedColumns.Count);
            table.SetAttributeValue("{urn:schemas-microsoft-com:office:spreadsheet}ExpandedRowCount", grid.Rows.Count + (generateColumnTitles ? 1 : 0));
            if (grid.RowHeight.IsAbsolute && setRowHeight)
            {
                table.SetAttributeValue("{urn:schemas-microsoft-com:office:spreadsheet}DefaultRowHeight", grid.RowHeight.Value);
            }

            //add the rows
            for (int i = generateColumnTitles ? -1 : 0; i < grid.Rows.Count; i++)
            {
                DataGridRow row = null;
                if (i >= 0)
                {
                    row = grid.Rows[i];
                }
                XElement rowElement = new XElement("{urn:schemas-microsoft-com:office:spreadsheet}Row");
                bool isFirstColumn = true;
                //add the columns
                for (int j = 0; j < orderedColumns.Count; j++)
                {
                    DataGridColumn column = orderedColumns[j];
                    //If is the row that contains the column titles
                    if (i == -1)
                    {
                        string columnTitle = column.GetColumnText();
                        XElement columnElement = new XElement("{urn:schemas-microsoft-com:office:spreadsheet}Column");
                        columnElement.SetAttributeValue("{urn:schemas-microsoft-com:office:spreadsheet}AutoFitWidth", column.Width.IsAbsolute ? 0 : 1);
                        if (column.Width.IsAbsolute && setColumnWidth)
                        {
                            columnElement.SetAttributeValue("{urn:schemas-microsoft-com:office:spreadsheet}Width", column.Width.Value);
                        }
                        table.Add(columnElement);
                        XElement titleElement = new XElement("{urn:schemas-microsoft-com:office:spreadsheet}Cell");
                        XElement titleDataElement = new XElement("{urn:schemas-microsoft-com:office:spreadsheet}Data", columnTitle);
                        titleDataElement.SetAttributeValue("{urn:schemas-microsoft-com:office:spreadsheet}Type", "String");
                        titleElement.Add(titleDataElement);
                        rowElement.Add(titleElement);
                    }
                    else
                    {
                        if (row.Type == DataGridRowType.Group)
                        {
                            if (isFirstColumn)
                            {
                                //output.Append(GetGroupText((DataGridGroupRow)row));
                            }
                        }
                        else
                        {
                            XElement cellElement = new XElement("{urn:schemas-microsoft-com:office:spreadsheet}Cell");
                            var cell = grid[row, column];
                            if (cell != null)
                            {
                                XElement cellDataElement = new XElement("{urn:schemas-microsoft-com:office:spreadsheet}Data", cell.Text);
                                cellDataElement.SetAttributeValue("{urn:schemas-microsoft-com:office:spreadsheet}Type", GetColumnExcelType(column));
                                cellElement.Add(cellDataElement);
                            }
                            rowElement.Add(cellElement);
                        }
                    }
                    isFirstColumn = false;
                }
                table.Add(rowElement);
            }
            return xml;
        }

        private static string GetColumnExcelType(DataGridColumn column)
        {
            //if (column is DataGridNumericColumn)
            //{
            //    return "Number";
            //}
            return "String";
        }

        private void btnExportExcel_Click(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Controls.SaveFileDialog();

            dialog.DefaultExt = "*.xml";
            dialog.Filter = "Excel Xml (*.xml)|*.xml|All files (*.*)|*.*";

            if (dialog.ShowDialog() == false) return;

            using (var sw = new StreamWriter(dialog.OpenFile()))
            {
                var excelContent = GetExcelFile(true, false, true);
                excelContent.Save(sw);
            }
        }
    }
}
