using MySqlConnector;
using skyscraper5.Mpeg2.Descriptors;
using skyscraper8.Skyscraper.Scraper.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace skyscraper5.Data.MySql
{
    public partial class MySqlDataStorage : DataStorage
    {
        private struct CatCoordinate
        {
            public int Nid { get; }
            public int Tsid { get; }
            public int Pid { get; }

            public CatCoordinate(int nid, int tsid, int pid)
            {
                Nid = nid;
                Tsid = tsid;
                Pid = pid;
            }

            public bool Equals(CatCoordinate other)
            {
                return Nid == other.Nid && Tsid == other.Tsid && Pid == other.Pid;
            }

            public override bool Equals(object obj)
            {
                return obj is CatCoordinate other && Equals(other);
            }

            public override int GetHashCode()
            {
                return HashCode.Combine(Nid, Tsid, Pid);
            }
        }

        private HashSet<CatCoordinate> _catCoordinates;

		public bool TestForCaSystem(int currentNetworkId, int currentTransportStreamId, int caDescriptorCaPid)
		{
			CatCoordinate coordinate = new CatCoordinate(currentNetworkId, currentTransportStreamId, caDescriptorCaPid);
			if (_catCoordinates == null)
				_catCoordinates = new HashSet<CatCoordinate>();
			if (_catCoordinates.Contains(coordinate))
				return true;

			using (MySqlConnection connection = new MySqlConnection(_mcsb.ToString()))
			{
				connection.Open();
				MySqlCommand mySqlCommand = connection.CreateCommand();
				mySqlCommand.CommandText =
					"SELECT dateadded FROM dvb_cat WHERE nid = @nid AND tsid = @tsid AND ca_pid = @ca_pid";
				mySqlCommand.Parameters.Add("@nid", MySqlDbType.Int32);
				mySqlCommand.Parameters.Add("@tsid", MySqlDbType.Int32);
				mySqlCommand.Parameters.Add("@ca_pid", MySqlDbType.Int32);
				mySqlCommand.Parameters["@nid"].Value = currentNetworkId;
				mySqlCommand.Parameters["@tsid"].Value = currentTransportStreamId;
				mySqlCommand.Parameters["@ca_pid"].Value = caDescriptorCaPid;
				MySqlDataReader dataReader = mySqlCommand.ExecuteReader();
				bool result = dataReader.Read();
				if (result)
					_catCoordinates.Add(coordinate);
				dataReader.Close();
				connection.Close();
				return result;
			}
		}

		public void StoreCaSystem(int currentNetworkId, int currentTransportStreamId, CaDescriptor caDescriptor)
		{
			CatCoordinate coordinate = new CatCoordinate(currentNetworkId, currentTransportStreamId, caDescriptor.CaPid);
			_catCoordinates.Add(coordinate);
			EnqueueSpeedhack(SpeedhackType.InsertCat, currentNetworkId, currentTransportStreamId, caDescriptor);
		}

	}
}
