using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using C1.Xaml.RichTextBox;
using C1.Xaml.RichTextBox.Documents;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml;
using Windows.UI;

namespace AppBar.Tools
{
    public static partial class EditExtensions
    {
        public static C1Table InsertTable(this C1TextPointer pos, int rows, int columns)
        {
            C1Table table = new C1Table()
           {
               BorderCollapse = true,
               Width = new C1Length(100, C1LengthUnitType.Percent),
           };

            var colWidth = new C1Length(Math.Floor(100.0 / columns), C1LengthUnitType.Percent);
            for (int col = 0; col < columns; ++col)
            {
                table.Columns.Add(new C1TableColumn() { Width = colWidth });
            }

            C1TableRowGroup tableRowGroup = new C1TableRowGroup();
            for (int row = 0; row < rows; ++row)
            {
                var tableRow = new C1TableRow();

                if (row == 0)
                {
                    table.Children.Add(tableRowGroup);
                }
                tableRowGroup.Children.Add(tableRow);

                for (int col = 0; col < columns; ++col)
                {
                    tableRow.Children.Add(new C1TableCell()
                    {
                        BorderBrush = new SolidColorBrush(Colors.Black),
                        BorderThickness = new Thickness(1),
                        Padding = new Thickness(7, 0, 7, 0),
                        Children = { new C1Paragraph() { Margin = new Thickness(), Children = { new C1Run() } } }
                    });
                }
            }
            while (!pos.Element.IsValidChild(typeof(C1Table)) && !pos.Element.IsRoot)
            {
                pos = pos.Split(true);
            }

            pos.Element.Children.Insert(pos.Offset, table);
            return table;
        }
    }
}
