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

namespace skyscraper5.Data.MySql
{
    public partial class MySqlDataStorage : DataStorage
    {
        private bool TestForDsmCcEvent(DateTime timestamp, int cnid, int ctsid, int pid, MySqlConnection connection)
        {
            MySqlCommand command = connection.CreateCommand();
            command.CommandText =
                "SELECT dateadded FROM dsmcc_events WHERE timestamp = @timestamp AND cnid = @cnid AND ctsid = @ctsid AND pid = @pid";
            command.Parameters.AddWithValue("@timestamp", timestamp);
            command.Parameters.AddWithValue("@cnid", cnid);
            command.Parameters.AddWithValue("@ctsid", ctsid);
            command.Parameters.AddWithValue("@pid", pid);
            MySqlDataReader dataReader = command.ExecuteReader();
            bool result = dataReader.Read();
            dataReader.Close();
            return result;
        }

		public void StoreDsmCcDoItNowEvent(DateTime value, int currentNetworkId, int currentTransportStreamId, int programNumber, StreamEventDescriptor descriptorListStreamEventDescriptor, int pid)
		{
			using (MySqlConnection connection = new MySqlConnection(_mcsb.ToString()))
			{
				connection.Open();
				if (!TestForDsmCcEvent(value, currentNetworkId, currentTransportStreamId, pid, connection))
				{
					MySqlCommand command = connection.CreateCommand();
					command.CommandText =
						"INSERT INTO dsmcc_events (timestamp, cnid, ctsid, progno, pid, event_id, npt_event_seconds, npt_event_microseconds, private_data) " +
						"VALUES (@timestamp, @cnid, @ctsid, @progno, @pid, @event_id, @npt_event_seconds, @npt_event_microseconds, @private_data)";
					command.Parameters.AddWithValue("@timestamp", value);
					command.Parameters.AddWithValue("@cnid", currentNetworkId);
					command.Parameters.AddWithValue("@ctsid", currentTransportStreamId);
					command.Parameters.AddWithValue("@progno", programNumber);
					command.Parameters.AddWithValue("@pid", pid);
					command.Parameters.AddWithValue("@event_id", descriptorListStreamEventDescriptor.EventId);
					command.Parameters.AddWithValue("@npt_event_seconds", descriptorListStreamEventDescriptor.NptEventSeconds);
					command.Parameters.AddWithValue("@npt_event_microseconds", descriptorListStreamEventDescriptor.NptEventMicroseconds);
					command.Parameters.Add("@private_data", MySqlDbType.TinyBlob);
					command.Parameters["@private_data"].Value = descriptorListStreamEventDescriptor.PrivateData;
					command.ExecuteNonQuery();
				}
				connection.Close();
			}
		}

	}
}
