using System;
using System.Windows.Forms;
using FastReport.Forms;
using FastReport.Utils;

namespace FastReport.AdvMatrix
{
    internal partial class MatrixHeaderEditorForm : BaseDialogForm
    {
        private HeaderDescriptor descr;
        private bool updating;
        private static int pageIndex = 0;

        private Report Report { get { return descr.Matrix.Report; } }

        private void Init()
        {
            updating = true;
            pcPages.ActivePageIndex = pageIndex;

            // General
            rbSimple.Checked = !descr.IsGroup;
            rbGroup.Checked = descr.IsGroup;
            rbGroup.Enabled = !descr.IsTopNItem;
            tbGroup.Text = descr.Expression;
            tbGroup.Report = Report;
            tbGroup.DataSource = descr.Matrix.DataSource;
            tbDisplayText.Text = descr.DisplayText;

            // Sort
            cbxSortOrder.SelectedIndex = (int)descr.Sort;
            rbSortByItemValue.Checked = String.IsNullOrEmpty(descr.SortByTotal);
            rbSortByTotal.Checked = !rbSortByItemValue.Checked;
            cbxSortByTotal.Items.AddRange(descr.GetAvailableTotals());
            cbxSortByTotal.SelectedIndex = cbxSortByTotal.FindStringExact(descr.SortByTotal);
            cbxInteractiveSort.Items.AddRange(descr.GetAvailableTotals());
            if (descr.InteractiveSort)
                cbxInteractiveSort.SelectedIndex = String.IsNullOrEmpty(descr.InteractiveSortBy) ? 1 : cbxInteractiveSort.FindStringExact(descr.InteractiveSortBy);
            else
                cbxInteractiveSort.SelectedIndex = 0; // NoSort
            cbxSortOrderToggledBy.Items.AddRange(descr.GetAvailableSortButtons());
            cbxSortOrderToggledBy.SelectedIndex = String.IsNullOrEmpty(descr.SortToggledBy) ? 0 : cbxSortOrderToggledBy.FindStringExact(descr.SortToggledBy);

            // Filter
            tbFilter.Text = descr.Filter;

            // TopN
            udTopN.Value = descr.TopN.Count;
            cbTopNTotal.Checked = descr.TopN.Total.Visible;
            tbTopNTotal.Text = descr.TopN.Total.Text;
            cbOthers.Checked = descr.TopN.Others.Visible;
            cbOthersTotal.Checked = descr.TopN.OthersTotal.Visible;
            tbOthersTotal.Text = descr.TopN.OthersTotal.Text;
            cbCreateItems.Checked = descr.TopNItemsPresent();

            // Visibility
            cbVisible.Checked = descr.Visible;
            cbVisible.Enabled = !descr.IsTopNItem;
            tbVisibleExpression.Text = descr.VisibleExpression;
            cbxVisibleToggledBy.Items.AddRange(descr.GetAvailableCollapseButtons());
            cbxVisibleToggledBy.SelectedIndex = cbxVisibleToggledBy.FindStringExact(descr.VisibleToggledBy);
            if (cbxVisibleToggledBy.SelectedIndex == -1)
                cbxVisibleToggledBy.SelectedIndex = 0;

            // Other
            cbStepped.Checked = descr.Stepped;
            cbMerge.Checked = descr.MergeSingleItem;
            cbPageBreak.Checked = descr.PageBreak;
            udColSpan.Value = descr.ColSpan;
            udRowSpan.Value = descr.RowSpan;

            updating = false;
        }

        private void Done()
        {
            pageIndex = pcPages.ActivePageIndex;

            if (DialogResult == DialogResult.OK)
            {
                // General
                descr.Expression = tbGroup.Text;
                descr.DisplayText = tbDisplayText.Text;

                // Sort and filter
                descr.Sort = (SortOrder)cbxSortOrder.SelectedIndex;
                descr.SortByTotal = rbSortByTotal.Checked && cbxSortByTotal.SelectedItem != null ? (string)cbxSortByTotal.SelectedItem : "";
                descr.InteractiveSort = cbxInteractiveSort.SelectedIndex != 0;
                descr.InteractiveSortBy = cbxInteractiveSort.SelectedIndex == 1 ? "" : (string)cbxInteractiveSort.SelectedItem;
                descr.SortToggledBy = cbxSortOrderToggledBy.SelectedIndex == 0 ? "" : (string)cbxSortOrderToggledBy.SelectedItem;

                // Filter
                descr.Filter = tbFilter.Text;

                // TopN
                if (!descr.IsTopNItem)
                {
                    descr.TopN.Count = (int)udTopN.Value;
                    descr.TopN.Total.Visible = cbTopNTotal.Checked;
                    descr.TopN.Total.Text = tbTopNTotal.Text;
                    descr.TopN.Others.Visible = cbOthers.Checked;
                    descr.TopN.OthersTotal.Visible = cbOthersTotal.Checked;
                    descr.TopN.OthersTotal.Text = tbOthersTotal.Text;
                    if (cbCreateItems.Checked && !descr.TopNItemsPresent())
                        descr.CreateTopNItems();
                    if (!cbCreateItems.Checked && descr.TopNItemsPresent())
                        descr.DeleteTopNItems();
                }

                // Visibility
                descr.Visible = cbVisible.Checked;
                descr.VisibleExpression = tbVisibleExpression.Text;
                descr.VisibleToggledBy = cbxVisibleToggledBy.SelectedIndex == 0 ? "" : (string)cbxVisibleToggledBy.SelectedItem;

                // Other
                bool steppedChanged = descr.Stepped != cbStepped.Checked;
                descr.Stepped = cbStepped.Checked;
                descr.MergeSingleItem = cbMerge.Checked;
                descr.PageBreak = cbPageBreak.Checked;
                descr.ColSpan = (int)udColSpan.Value;
                descr.RowSpan = (int)udRowSpan.Value;

                if (steppedChanged)
                {
                    foreach (HeaderDescriptor child in descr.Items)
                    {
                        if (child.IsGroup)
                        {
                            Padding p = child.TemplateCell.Padding;
                            if (descr.Stepped)
                                p.Left = descr.TemplateCell.Padding.Left + 20;
                            else
                                p.Left = descr.TemplateCell.Padding.Left;
                            child.TemplateCell.Padding = p;
                            descr.TemplateCell.HorzAlign = HorzAlign.Left;
                            child.TemplateCell.HorzAlign = HorzAlign.Left;
                            break;
                        }
                    }
                }
            }
        }

        public override void Localize()
        {
            base.Localize();

            Text = Res.Get("Forms,AdvMatrixHeaderEditor");
            MyRes res = new MyRes("Forms,AdvMatrixHeaderEditor,General");
            pnGeneral.Text = res.Get("");
            lblItemType.Text = res.Get("ItemType");
            rbSimple.Text = res.Get("Simple");
            rbGroup.Text = res.Get("Group");
            lblDisplayText.Text = res.Get("DisplayText");

            res = new MyRes("Forms,AdvMatrixHeaderEditor,Sort");
            pnSort.Text = res.Get("");
            lblSortOrder.Text = res.Get("SortOrder");
            lblSortBy.Text = res.Get("SortBy");
            rbSortByItemValue.Text = res.Get("ItemValue");
            rbSortByTotal.Text = res.Get("TotalValue");
            lblInteractiveSort.Text = res.Get("InteractiveSortBy");
            cbxInteractiveSort.Items.Add(Res.Get("Misc,None"));
            cbxInteractiveSort.Items.Add(res.Get("Auto"));
            lblSortOrderToggledBy.Text = res.Get("SortOrderToggledBy");
            cbxSortOrderToggledBy.Items.Add(Res.Get("Misc,None"));
            res = new MyRes("Forms,GroupBandEditor");
            cbxSortOrder.Items.Add(res.Get("NoSort"));
            cbxSortOrder.Items.Add(res.Get("Ascending"));
            cbxSortOrder.Items.Add(res.Get("Descending"));

            res = new MyRes("Forms,AdvMatrixHeaderEditor,Filter");
            pnFilter.Text = res.Get("");
            lblFilter.Text = res.Get("Filter");

            res = new MyRes("Forms,AdvMatrixHeaderEditor,TopN");
            pnTopN.Text = res.Get("");
            lblTopNCount.Text = res.Get("Count");
            lblAdditionalItems.Text = res.Get("AdditionalItems");
            cbTopNTotal.Text = res.Get("TopNTotal");
            cbOthers.Text = res.Get("Others");
            cbOthersTotal.Text = res.Get("OthersTotal");
            cbCreateItems.Text = res.Get("Create");
            
            res = new MyRes("Forms,AdvMatrixHeaderEditor,Visibility");
            pnVisibility.Text = res.Get("");
            cbVisible.Text = res.Get("Visible");
            lblVisibleExpression.Text = res.Get("VisibleExpression");
            lblVisibleToggledBy.Text = res.Get("VisibleToggledBy");
            cbxVisibleToggledBy.Items.Add(Res.Get("Misc,None"));

            res = new MyRes("Forms,AdvMatrixHeaderEditor,Other");
            pnOther.Text = res.Get("");
            cbStepped.Text = res.Get("Stepped");
            cbMerge.Text = res.Get("Merge");
            cbPageBreak.Text = res.Get("PageBreak");
            lblColSpan.Text = res.Get("ColSpan");
            lblRowSpan.Text = res.Get("RowSpan");
        }

        public override void UpdateDpiDependencies()
        {
            base.UpdateDpiDependencies();
            tbDisplayText.Image = this.GetImage(68);
            tbFilter.Image = this.GetImage(52);
            tbVisibleExpression.Image = this.GetImage(52);
        }

        public MatrixHeaderEditorForm(HeaderDescriptor descr)
        {
            this.descr = descr;
            InitializeComponent();
            Localize();
            Init();
            UIUtils.CheckRTL(this);
            UpdateDpiDependencies();
        }

        private void MatrixHeaderEditorForm_Shown(object sender, EventArgs e)
        {
            updating = true;
            rbGroup_CheckedChanged(this, EventArgs.Empty);
            udTopN_ValueChanged(this, EventArgs.Empty);
            updating = false;
        }

        private void MatrixHeaderEditorForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Done();
        }

        private void rbGroup_CheckedChanged(object sender, EventArgs e)
        {
            bool isGroup = rbGroup.Checked;
            tbGroup.Enabled = isGroup;
            pnSort.Enabled = isGroup;
            pnTopN.Enabled = isGroup;
            cbxInteractiveSort.Enabled = isGroup;

            if (!updating)
            {
                tbDisplayText.Text = "";
                if (rbSimple.Checked)
                    tbGroup.Text = "";
            }
            if (rbSimple.Checked)
                tbDisplayText.FocusTextBox();
            else
                tbGroup.Focus();
        }

        private void rbSortByTotal_CheckedChanged(object sender, EventArgs e)
        {
            cbxSortByTotal.Enabled = rbSortByTotal.Checked;
            if (!updating)
            {
                if (rbSortByTotal.Checked && cbxSortByTotal.Items.Count > 0)
                    cbxSortByTotal.SelectedIndex = 0;
                else
                    cbxSortByTotal.SelectedIndex = -1;
            }
        }

        private void tbDisplayText_ButtonClick(object sender, EventArgs e)
        {
            using (TextEditorForm form = new TextEditorForm(Report))
            {
                form.ExpressionText = tbDisplayText.Text;
                form.Brackets = descr.TemplateCell.Brackets;
                if (form.ShowDialog() == DialogResult.OK)
                {
                    tbDisplayText.Text = form.ExpressionText;
                }
            }
        }

        private void tbFilter_ButtonClick(object sender, EventArgs e)
        {
            tbFilter.Text = Editors.EditExpression(Report, tbFilter.Text);
        }

        private void udTopN_ValueChanged(object sender, EventArgs e)
        {
            bool enabled = udTopN.Value > 0;
            pnTopNControls.Enabled = enabled;
            if (!enabled)
                cbCreateItems.Checked = false;
        }

        private void tbVisibleExpression_ButtonClick(object sender, EventArgs e)
        {
            tbVisibleExpression.Text = Editors.EditExpression(Report, tbVisibleExpression.Text);
        }
    }
}
