using System;
using FastReport.Data;
using FastReport.Table;

namespace FastReport.AdvMatrix
{
    internal class MatrixCellSmartTag : DataColumnSmartTag
    {
        private AdvMatrixObject matrix;
        private TableCell cell;

        protected override DataSourceBase FindRootDataSource()
        {
            return matrix.DataSource;
        }

        private void SetExpression(TableCell cell, string expression)
        {
            switch (cell.GetMatrixElement())
            {
                case MatrixElement.Corner:
                    cell.Text = expression;
                    break;
                case MatrixElement.Column:
                case MatrixElement.Row:
                    HeaderDescriptor descr = cell.GetHeaderDescriptor();
                    descr.Expression = expression;
                    descr.DisplayText = "";
                    cell.Text = expression;
                    break;
                case MatrixElement.Cell:
                    cell.ChangeExpression(expression);
                    break;
            }
        }

        protected override void ItemClicked()
        {
            string expression = String.IsNullOrEmpty(DataColumn) ? "" : "[" + DataColumn + "]";

            if (!cell.IsSelected)
            {
                SetExpression(cell, expression);
            }
            else
            {
                foreach (Base c in Designer.SelectedObjects)
                {
                    TableCell cell = c as TableCell;
                    if (cell != null)
                    {
                        SetExpression(cell, expression);
                    }
                }
            }

            matrix.UpdateDescriptors(true);
            base.ItemClicked();
        }

        public MatrixCellSmartTag(AdvMatrixObject matrix, TableCell cell) : base(cell)
        {
            this.matrix = matrix;
            this.cell = cell;

            string expression = cell.Text;
            switch (cell.GetMatrixElement())
            {
                case MatrixElement.Column:
                case MatrixElement.Row:
                    expression = cell.GetHeaderDescriptor().Expression;
                    break;
                case MatrixElement.Cell:
                    CellDescriptor cellDescr = cell.GetDescriptor();
                    if (cellDescr.Aggregates.Count == 1)
                        expression = cellDescr.Aggregates[0].Expression;
                    break;
            }
            
            if (expression.StartsWith("[") && expression.EndsWith("]"))
                expression = expression.Substring(1, expression.Length - 2);
            DataColumn = expression;
        }
    }
}
