using System;
using System.Collections.Generic;
using System.Linq;
using InABox.Core;
using Syncfusion.SfDataGrid.XForms;

namespace InABox.Mobile
{
    public class MobileGridColumns
    {
        private SfDataGrid _grid;
        private List<IMobileGridColumn> _columns;
        private bool _updating;

        public IMobileGridColumn this[int index] => _columns[index];

        public event EventHandler Changed;
        
        public MobileGridColumns(SfDataGrid grid)
        {
            _grid = grid;
            _columns = new List<IMobileGridColumn>();
        }

        private void Update()
        {
            if (_updating)
                return;
            
            _grid.Columns.Suspend();
            
            _grid.Columns.Clear();
            
            foreach (var column in _columns)
                _grid.Columns.Add(column.CreateColumn());

            _grid.TableSummaryRows.Clear();
            var summaries = _columns.OfType<IMobileGridSummaryColumn>()
                .Where(x => x.Summary != MobileGridSummaryType.None).ToArray();
            if (summaries.Any())
            {
                var row = new GridTableSummaryRow() { ShowSummaryInRow = false };
                foreach (var summary in summaries)
                    row.SummaryColumns.Add(summary.CreateSummaryColumn());
                _grid.TableSummaryRows.Add(row);
            }
            
            _grid.Columns.Resume();
            _grid.RefreshColumns();
            Changed?.Invoke(this, EventArgs.Empty);

        }

        public MobileGridColumns BeginUpdate()
        {
            _updating = true;
            return this;
        }

        public MobileGridColumns EndUpdate()
        {
            _updating = false;
            Update();
            return this;
        }

        public MobileGridColumns Clear()
        {
            _columns.Clear();
            Update();
            return this;
        }

        public MobileGridColumns Add(IMobileGridColumn column)
        {
            _columns.Add(column);
            Update();
            return this;
        }


        
    }
}