using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CarbonLib.Carbon.Models
{
    public class GamsThreeKeyParameter
    {
        //field, year, crop
        public Dictionary<(string,int,string), List<ColumnValue>> TrippleKeyParam { get; set; }

        public GamsThreeKeyParameter()
        {
            TrippleKeyParam = new Dictionary<(string, int, string), List<ColumnValue>>();
        }

        public void AddValue((string, int, string)key, string column, double value)
        {
            if (TrippleKeyParam.ContainsKey(key))
            {
                if (TrippleKeyParam[key].Any(x => x.Key == column))
                {
                    throw new Exception("key allready exists");
                }
                else
                {
                    TrippleKeyParam[key].Add(new ColumnValue(column, value));
                }
            }
            else
            {
                TrippleKeyParam.Add(key, new List<ColumnValue> { new ColumnValue(column, value) });
            }
        }

        public void AddOrUpdateValue((string, int, string) key, string column, double value)
        {
            if (TrippleKeyParam.ContainsKey(key))
            {
                if (TrippleKeyParam[key].Any(x => x.Key == column))
                {
                    TrippleKeyParam[key].Single(x => x.Key == column).Value = value;
                }
                else
                {
                    TrippleKeyParam[key].Add(new ColumnValue(column, value));
                }
            }
            else
            {
                TrippleKeyParam.Add(key, new List<ColumnValue> { new ColumnValue(column, value) });
            }
        }

        public void AddValueSkipIfColumnExists((string, int, string) key, string column, double value)
        {
            if (TrippleKeyParam.ContainsKey(key))
            {
                if (TrippleKeyParam[key].Any(x => x.Key == column))
                {
                    return;
                }
                else
                {
                    TrippleKeyParam[key].Add(new ColumnValue(column, value));
                }
            }
            else
            {
                TrippleKeyParam.Add(key, new List<ColumnValue> { new ColumnValue(column, value) });
            }
        }

        public List<(string, int, string)> KeysWhereCropKeyExists(int year, string crop)
        {
            return TrippleKeyParam.Where(x => x.Key.Item2 == year && x.Key.Item3.ToLower() == crop.ToLower()).Select(s=>s.Key).ToList();
        }
    }
}
