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

namespace skyscraper5.Data.MySql
{
    public partial class MySqlDataStorage : DataStorage
    {
        private bool TestForPatEntry(int currentNetworkId, int currentTransportStreamId, ushort programId, MySqlConnection connection)
        {
            PmtCoordinate coordinate = new PmtCoordinate(currentNetworkId, currentTransportStreamId, programId);

            MySqlCommand command = connection.CreateCommand();
            command.CommandText =
                "SELECT dateadded FROM dvb_pat WHERE cnid = @cnid AND ctsid = @ctsid AND program_id = @program_id";
            command.Parameters.AddWithValue("@cnid", currentNetworkId);
            command.Parameters.AddWithValue("@ctsid", currentTransportStreamId);
            command.Parameters.AddWithValue("@program_id", programId);
            MySqlDataReader dataReader = command.ExecuteReader();
            bool result = dataReader.Read();
            if (result)
            {
                knownPats.Add(coordinate);
            }
            dataReader.Close();
            return result;
        }

        private HashSet<PmtCoordinate> knownPats;

		public bool StorePatEntry(int currentNetworkId, int currentTransportStreamId, int pmtPid, ushort programId)
		{
			if (knownPats == null)
				knownPats = new HashSet<PmtCoordinate>();
			PmtCoordinate coordinate = new PmtCoordinate(currentNetworkId, currentTransportStreamId, programId);
			if (knownPats.Contains(coordinate))
				return false;

			using (MySqlConnection connection = new MySqlConnection(_mcsb.ToString()))
			{
				connection.Open();
				int result = 0;
				if (!TestForPatEntry(currentNetworkId, currentTransportStreamId, programId, connection))
				{
					EnqueueSpeedhack(SpeedhackType.StorePat, currentNetworkId, currentTransportStreamId, pmtPid, programId);
					knownPats.Add(coordinate);
				}
				connection.Close();
				return result > 0;
			}
		}

	}
}
