using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using FMSAdmin.Data;

namespace FMSAdmin.Helpers {
    public class FormulaTableManager {
        private FMSContext _context;
        Dictionary<string, TableComparerValue[]> tables;

        public FormulaTableManager(FMSContext context) {
            _context = context;
            tables = new Dictionary<string, TableComparerValue[]>();
        }

        public TableComparerValue[] GetTableValues(string functionName) {
            TableComparerValue[] values;
            if (this.tables.ContainsKey(functionName)) {
                values = this.tables[functionName];
            } else {
                var queryTable = from table in _context.BemsFormulaTable
                                 from value in _context.BemsFormulaTableValue
                                 where table.FunctionName == functionName &&
                                    table.TableId == value.TableId
                                 select new TableComparerValue {
                                     XValue = value.XValue,
                                     YValue = value.YValue
                                 };
                if (queryTable.Any() == false) {
                    return null;
                }
                values = queryTable.ToArray();
            }
            return values;
        }

        public class TableComparerValue : IComparable<TableComparerValue> {
            public double XValue { get; set; }
            public double YValue { get; set; }

            public int CompareTo(TableComparerValue other) {
                var otherXValue = other.XValue;
                if (XValue < otherXValue) {
                    return -1;
                } else if (XValue > otherXValue) {
                    return 1;
                }
                return 0;
            }
        };
    }
}
