using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MySqlConnector;
using skyscraper5.Dvb.Descriptors;
using skyscraper5.Dvb.Psi.Model;
using skyscraper5.Mpeg2.Descriptors;
using skyscraper5.Mpeg2.Psi.Model;
using static skyscraper5.Dvb.Descriptors.ContentIdentifierDescriptor;
using System.Diagnostics.Metrics;
using skyscraper8.Skyscraper.Scraper.Storage;

namespace skyscraper5.Data.MySql
{
    public partial class MySqlDataStorage : DataStorage
    {
        private enum SpeedhackType
        {
            UpdateTdt,
            InsertTdt,
            UpdateTimeOffset,
            InsertTimeOffset,
            StorePat,
            InsertPmt,
            InsertTsdt,
            UpdateTsdtStationIdentification,
            InsertSdt,
            InsertCat,
            InsertBatTs,
            InsertNitTransportStream,
            UpdateSdt,
            UpdateNitTransportStream
        }

        private Queue<KeyValuePair<SpeedhackType, object[]>> _speedhackQueue;
        private Thread _speedhackThread;
        private bool _waitingForSpeedhacksToComplete;

        private bool IsSpeedhackThreadAlive()
        {
            if (_speedhackThread == null)
                return false;

            if (!_speedhackThread.IsAlive)
                return false;

            return true;
        }

        private void EnqueueSpeedhack(SpeedhackType hackType, params object[] args)
        {
            if (_speedhackQueue == null)
                _speedhackQueue = new Queue<KeyValuePair<SpeedhackType, object[]>>();

            lock (_speedhackQueue)
            {
                _speedhackQueue.Enqueue(new KeyValuePair<SpeedhackType, object[]>(hackType, args));
            }

            if (!IsSpeedhackThreadAlive())
            {
                _speedhackThread = new Thread(RunSpeedhackThread);
                _speedhackThread.Name = "PSI Writer";
                _speedhackThread.Priority = ThreadPriority.Lowest;
                _speedhackThread.Start();
            }
        }

        private void RunSpeedhackThread()
        {
            using (MySqlConnection connection = new MySqlConnection(_mcsb.ToString()))
            {
                connection.Open();
                while (_speedhackQueue.Count > 0)
                {
                    KeyValuePair<SpeedhackType, object[]> speedhackJob;
                    lock (_speedhackQueue)
                    {
                        if (_waitingForSpeedhacksToComplete)
                        {
                            if (_speedhackQueue.Count > 0 && _speedhackQueue.Count % 100 == 0)
                            {
                                Console.WriteLine("{0} SQLs in queue...", _speedhackQueue.Count);
                            }
                        }
                        speedhackJob = _speedhackQueue.Dequeue();
                    }

                    object[] args = speedhackJob.Value;
                    MySqlTransaction transaction;
                    switch (speedhackJob.Key)
                    {
                        case SpeedhackType.UpdateTdt:
                            UpdateTdt(connection, (int)args[0], (int)args[1], (DateTime)args[2]);
                            break;
                        case SpeedhackType.UpdateTimeOffset:
                            transaction = connection.BeginTransaction();
                            UpdateTimeOffset(transaction, (int)args[0], (int)args[1], (DateTime)args[2], (LocalTimeOffsetDescriptor.LocalTime)args[3]);
                            transaction.Commit();
                            break;
                        case SpeedhackType.InsertTdt:
                            InsertTdt(connection, (int)args[0], (int)args[1], (DateTime)args[2]);
                            break;
                        case SpeedhackType.InsertTimeOffset:
                            transaction = connection.BeginTransaction();
                            UpdateTimeOffset(transaction, (int)args[0], (int)args[1], (DateTime)args[2], (LocalTimeOffsetDescriptor.LocalTime)args[3]);
                            transaction.Commit();
                            break;
                        case SpeedhackType.StorePat:
                            MySqlCommand command = connection.CreateCommand();
                            command.CommandText = "INSERT INTO dvb_pat (cnid, ctsid, pmt_pid, program_id) VALUES (@cnid, @ctsid, @pmt_pid, @program_id)";
                            command.Parameters.AddWithValue("@cnid", (int)args[0]);
                            command.Parameters.AddWithValue("@ctsid", (int)args[1]);
                            command.Parameters.AddWithValue("@pmt_pid", (int)args[2]);
                            command.Parameters.AddWithValue("@program_id", (ushort)args[3]);
                            command.ExecuteNonQuery();
                            break;
                        case SpeedhackType.InsertPmt:
                            InsertPmt(connection, (int)args[0], (int)args[1], (ProgramMapping)args[2]);
                            break;
                        case SpeedhackType.InsertTsdt:
                            InsertTsdt(connection, (TsdtCoordinate)args[0]);
                            break;
                        case SpeedhackType.UpdateTsdtStationIdentification:
                            UpdateTsdtStationIdentification(connection, (int)args[0], (int)args[1], (string)args[2]);
                            break;
                        case SpeedhackType.InsertSdt:
                            InsertSdt(connection, (ushort)args[0], (ushort)args[1], (SdtService)args[2]);
                            break;
                        case SpeedhackType.InsertCat:
                            InsertCat(connection, (int)args[0], (int)args[1], (CaDescriptor)args[2]);
                            break;
                        case SpeedhackType.InsertBatTs:
                            InsertBatTs(connection, (ushort)args[0], (BatTransportStream)args[1]);
                            break;
                        case SpeedhackType.InsertNitTransportStream:
                            InsertNitTransportStream(connection, (ushort)args[0], (NitTransportStream)args[1]);
                            break;
                        case SpeedhackType.UpdateSdt:
                            UpdateSdt(connection, (ushort)args[0], (ushort)args[1], (SdtService)args[2]);
                            break;
                        case SpeedhackType.UpdateNitTransportStream:
                            SqlUpdateNitTransportStream(connection, (ushort)args[0], (NitTransportStream)args[1]);
                            break;
                        default:
                            throw new NotImplementedException(speedhackJob.Key.ToString());
                    }
                }
                connection.Close();
            }
        }

        private void SqlUpdateNitTransportStream(MySqlConnection connection, ushort networkId, NitTransportStream newer)
        {
            MySqlCommand mySqlCommand = connection.CreateCommand();
            mySqlCommand.CommandText =
                "UPDATE dvb_nit_transport_stream " +
                "SET onid = @onid, delivery_method = @delivery_method, east = @east, fec_inner = @fec_inner, frequency = @frequency, orbital_position = @orbital_position, polarization = @polarization, roll_off = @roll_off, s2 = @s2, symbol_rate = @symbol_rate, scrambling_sequence_index = @scrambling_sequence_index, input_stream_identifier = @input_stream_identifier, timeslice_number = @timeslice_number, ts_gs_mode = @ts_gs_mode, private_data_specifier_id = @private_data_specifier_id, tfs_flag = @tfs_flag, bandwidth = @bandwidth, guard_interval = @guard_interval, other_frequency_flag = @other_frequency_flag, plp_id = @plp_id, siso_miso = @siso_miso, t2_system_id = @t2_system_id, transmission_mode = @transmission_mode, coding_type = @coding_type, modulation_type = @modulation_type, fec_outer = @fec_outer, code_rate_hp_stream = @code_rate_hp_stream, code_rate_lp_stream = @code_rate_lp_stream, hierarchy_information = @hierarchy_information, mpe_fec_indicator = @mpe_fec_indicator, priority = @priority, time_slicing_indicator = @time_slicing_indicator, network_name = @network_name, target_region_country_code = @target_region_country_code, numupdates = numupdates + 1, dateupdated = CURRENT_TIMESTAMP " +
                "WHERE nid = @nid " +
                "AND tsid = @tsid";
            mySqlCommand.Parameters.Add("@nid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@tsid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@onid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@delivery_method", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@east", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@fec_inner", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@frequency", MySqlDbType.Int64);
            mySqlCommand.Parameters.Add("@orbital_position", MySqlDbType.Float);
            mySqlCommand.Parameters.Add("@polarization", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@roll_off", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@s2", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@symbol_rate", MySqlDbType.Int64);
            mySqlCommand.Parameters.Add("@scrambling_sequence_index", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@input_stream_identifier", MySqlDbType.Int16);
            mySqlCommand.Parameters.Add("@timeslice_number", MySqlDbType.Int16);
            mySqlCommand.Parameters.Add("@ts_gs_mode", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@private_data_specifier_id", MySqlDbType.Int64);
            mySqlCommand.Parameters.Add("@tfs_flag", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@bandwidth", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@guard_interval", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@other_frequency_flag", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@plp_id", MySqlDbType.Int16);
            mySqlCommand.Parameters.Add("@siso_miso", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@t2_system_id", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@transmission_mode", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@coding_type", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@modulation_type", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@fec_outer", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@code_rate_hp_stream", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@code_rate_lp_stream", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@hierarchy_information", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@mpe_fec_indicator", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@priority", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@time_slicing_indicator", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@network_name", MySqlDbType.VarChar);
            mySqlCommand.Parameters.Add("@target_region_country_code", MySqlDbType.VarChar);
            mySqlCommand.Parameters["@nid"].Value = networkId;
            mySqlCommand.Parameters["@tsid"].Value = newer.TransportStreamId;
            mySqlCommand.Parameters["@onid"].Value = newer.OriginalNetworkId;
            mySqlCommand.Parameters["@delivery_method"].Value = (int?)newer.DeliveryMethod;
            mySqlCommand.Parameters["@east"].Value = newer.East;
            mySqlCommand.Parameters["@fec_inner"].Value = (int?)newer.FecInner;
            mySqlCommand.Parameters["@frequency"].Value = newer.Frequency;
            mySqlCommand.Parameters["@orbital_position"].Value = newer.OrbitalPosition;
            mySqlCommand.Parameters["@polarization"].Value = (int?)newer.Polarization;
            mySqlCommand.Parameters["@roll_off"].Value = newer.RollOff;
            mySqlCommand.Parameters["@s2"].Value = newer.S2;
            mySqlCommand.Parameters["@symbol_rate"].Value = newer.SymbolRate;
            mySqlCommand.Parameters["@scrambling_sequence_index"].Value = newer.ScramblingSequenceIndex;
            mySqlCommand.Parameters["@input_stream_identifier"].Value = newer.InputStreamIdentifier;
            mySqlCommand.Parameters["@timeslice_number"].Value = newer.TimesliceNumber;
            mySqlCommand.Parameters["@ts_gs_mode"].Value = (int?)newer.TsGsMode;
            mySqlCommand.Parameters["@private_data_specifier_id"].Value = newer.PrivateDataSpecifierId;
            mySqlCommand.Parameters["@tfs_flag"].Value = newer.TfsFlag;
            mySqlCommand.Parameters["@bandwidth"].Value = newer.Bandwidth;
            mySqlCommand.Parameters["@guard_interval"].Value = newer.GuardInterval;
            mySqlCommand.Parameters["@other_frequency_flag"].Value = newer.OtherFrequencyFlag;
            mySqlCommand.Parameters["@plp_id"].Value = newer.PlpId;
            mySqlCommand.Parameters["@siso_miso"].Value = newer.SisoMiso;
            mySqlCommand.Parameters["@t2_system_id"].Value = newer.T2SystemId;
            mySqlCommand.Parameters["@transmission_mode"].Value = newer.TransmissionMode;
            mySqlCommand.Parameters["@coding_type"].Value = (int?)newer.CodingType;
            mySqlCommand.Parameters["@modulation_type"].Value = newer.ModulationType;
            mySqlCommand.Parameters["@fec_outer"].Value = (int?)newer.FecOuter;
            mySqlCommand.Parameters["@code_rate_hp_stream"].Value = (int?)newer.CodeRateHpStream;
            mySqlCommand.Parameters["@code_rate_lp_stream"].Value = (int?)newer.CodeRateLpStream;
            mySqlCommand.Parameters["@hierarchy_information"].Value = (int?)newer.HierarchyInformation;
            mySqlCommand.Parameters["@mpe_fec_indicator"].Value = newer.MpeFecIndicator;
            mySqlCommand.Parameters["@priority"].Value = newer.Priority;
            mySqlCommand.Parameters["@time_slicing_indicator"].Value = newer.TimeSlicingIndicator;
            mySqlCommand.Parameters["@network_name"].Value = newer.NetworkName;
            mySqlCommand.Parameters["@target_region_country_code"].Value = newer.TargetRegionCountryCode;
            SetNulls(mySqlCommand);
            mySqlCommand.ExecuteNonQuery();

        }

        private void UpdateSdt(MySqlConnection connection, ushort transportStreamId, ushort originalNetworkId, SdtService newer)
        {
            MySqlCommand mySqlCommand = connection.CreateCommand();
            mySqlCommand.CommandText = "UPDATE dvb_sdt " +
                                       "SET eit_schedule = @eit_schedule, eit_schedule_following = @eit_schedule_following, running_status = @running_status, free_ca_mode = @free_ca_mode, service_name = @service_name, service_provider_name = @service_provider_name, service_type = @service_type, private_data_specifier = @private_data_specifier, component_tag = @component_tag, iso_639_language_code = @iso_639_language_code, text = @text, data_broadcast_id = @data_broadcast_id, selector = @selector, reference_service_id = @reference_service_id, default_authority = @default_authority, control_remote_access_over_internet = @control_remote_access_over_internet, do_not_apply_revocation = @do_not_apply_revocation, do_not_scramble = @do_not_scramble, old_onid = @old_onid, old_service_id = @old_service_id, old_tsid = @old_tsid, num_updates = num_updates + 1, dateupdated = CURRENT_TIMESTAMP " +
                                       "WHERE tsid = @tsid " +
                                       "AND onid = @onid " +
                                       "AND service_id = @service_id";
            mySqlCommand.Parameters.Add("@tsid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@onid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@service_id", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@eit_schedule", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@eit_schedule_following", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@running_status", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@free_ca_mode", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@service_name", MySqlDbType.VarChar);
            mySqlCommand.Parameters.Add("@service_provider_name", MySqlDbType.VarChar);
            mySqlCommand.Parameters.Add("@service_type", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@private_data_specifier", MySqlDbType.Int64);
            mySqlCommand.Parameters.Add("@component_tag", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@iso_639_language_code", MySqlDbType.VarChar);
            mySqlCommand.Parameters.Add("@text", MySqlDbType.VarChar);
            mySqlCommand.Parameters.Add("@data_broadcast_id", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@selector", MySqlDbType.TinyBlob);
            mySqlCommand.Parameters.Add("@reference_service_id", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@control_remote_access_over_internet", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@do_not_apply_revocation", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@do_not_scramble", MySqlDbType.Bool);
            mySqlCommand.Parameters.Add("@old_onid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@old_service_id", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@old_tsid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@default_authority", MySqlDbType.VarChar);
            mySqlCommand.Parameters["@tsid"].Value = transportStreamId;
            mySqlCommand.Parameters["@onid"].Value = originalNetworkId;
            mySqlCommand.Parameters["@service_id"].Value = newer.ServiceId;
            mySqlCommand.Parameters["@eit_schedule"].Value = newer.EitScheduleFlag;
            mySqlCommand.Parameters["@eit_schedule_following"].Value = newer.EitPresentFollowingFlag;
            mySqlCommand.Parameters["@running_status"].Value = (int)newer.RunningStatus;
            mySqlCommand.Parameters["@free_ca_mode"].Value = newer.FreeCaMode;
            mySqlCommand.Parameters["@service_name"].Value = newer.ServiceName;
            mySqlCommand.Parameters["@service_provider_name"].Value = newer.ServiceProviderName;
            mySqlCommand.Parameters["@service_type"].Value = (int?)newer.ServiceType;
            mySqlCommand.Parameters["@private_data_specifier"].Value = newer.PrivateDataSpecifier;
            mySqlCommand.Parameters["@component_tag"].Value = newer.ComponentTag;
            mySqlCommand.Parameters["@iso_639_language_code"].Value = newer.Iso639LanguageCode;
            mySqlCommand.Parameters["@text"].Value = newer.Text;
            mySqlCommand.Parameters["@data_broadcast_id"].Value = newer.DataBroadcastId;
            mySqlCommand.Parameters["@selector"].Value = newer.Selector;
            mySqlCommand.Parameters["@reference_service_id"].Value = newer.ReferenceServiceId;
            mySqlCommand.Parameters["@control_remote_access_over_internet"].Value = newer.ControlRemoteAccessOverInternet;
            mySqlCommand.Parameters["@do_not_apply_revocation"].Value = newer.DoNotApplyRevocation;
            mySqlCommand.Parameters["@do_not_scramble"].Value = newer.DoNotScramble;
            mySqlCommand.Parameters["@old_onid"].Value = newer.OldOriginalNetworkId;
            mySqlCommand.Parameters["@old_service_id"].Value = newer.OldServiceId;
            mySqlCommand.Parameters["@old_tsid"].Value = newer.OldTransportStreamId;
            mySqlCommand.Parameters["@default_authority"].Value = newer.DefaultAuthority;

            SetNulls(mySqlCommand);
            mySqlCommand.ExecuteNonQuery();

        }

        private void InsertNitTransportStream(MySqlConnection connection, ushort networkId, NitTransportStream transportStream)
        {
            Guid uuid = Guid.Empty;
            bool hasLinkages = HasLinkages(transportStream.Linkages);
            if (hasLinkages)
                uuid = Guid.NewGuid();
            {
                MySqlTransaction transaction = connection.BeginTransaction();
                MySqlCommand mySqlCommand = connection.CreateCommand();
                mySqlCommand.Transaction = transaction;
                mySqlCommand.CommandText =
                    "INSERT INTO dvb_nit_transport_stream " +
                    "    (nid, tsid, onid, delivery_method, east, fec_inner, frequency, orbital_position, polarization, roll_off, s2, symbol_rate, scrambling_sequence_index, input_stream_identifier, timeslice_number, ts_gs_mode, private_data_specifier_id, tfs_flag, bandwidth, guard_interval, other_frequency_flag, plp_id, siso_miso, t2_system_id, transmission_mode, coding_type, modulation_type, fec_outer, code_rate_hp_stream, code_rate_lp_stream, hierarchy_information, mpe_fec_indicator, priority, time_slicing_indicator, network_name, target_region_country_code, uuid) " +
                    "VALUES" +
                    "    (@nid, @tsid, @onid, @delivery_method, @east, @fec_inner, @frequency, @orbital_position, @polarization, @roll_off, @s2, @symbol_rate, " +
                    "     @scrambling_sequence_index, @input_stream_identifier, @timeslice_number, @ts_gs_mode, @private_data_specifier_id, @tfs_flag, @bandwidth, " +
                    "     @guard_interval, @other_frequency_flag, @plp_id, @siso_miso, @t2_system_id, @transmission_mode, @coding_type, @modulation_type, @fec_outer, " +
                    "     @code_rate_hp_stream, @code_rate_lp_stream, @hierarchy_information, @mpe_fec_indicator, @priority, @time_slicing_indicator, @network_name, " +
                    "     @target_region_country_code, @uuid)";
                mySqlCommand.Parameters.Add("@nid", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@tsid", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@onid", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@delivery_method", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@east", MySqlDbType.Bool);
                mySqlCommand.Parameters.Add("@fec_inner", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@frequency", MySqlDbType.Int64);
                mySqlCommand.Parameters.Add("@orbital_position", MySqlDbType.Float);
                mySqlCommand.Parameters.Add("@polarization", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@roll_off", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@s2", MySqlDbType.Bool);
                mySqlCommand.Parameters.Add("@symbol_rate", MySqlDbType.Int64);
                mySqlCommand.Parameters.Add("@scrambling_sequence_index", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@input_stream_identifier", MySqlDbType.Int16);
                mySqlCommand.Parameters.Add("@timeslice_number", MySqlDbType.Int16);
                mySqlCommand.Parameters.Add("@ts_gs_mode", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@private_data_specifier_id", MySqlDbType.Int64);
                mySqlCommand.Parameters.Add("@tfs_flag", MySqlDbType.Bool);
                mySqlCommand.Parameters.Add("@bandwidth", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@guard_interval", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@other_frequency_flag", MySqlDbType.Bool);
                mySqlCommand.Parameters.Add("@plp_id", MySqlDbType.Int16);
                mySqlCommand.Parameters.Add("@siso_miso", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@t2_system_id", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@transmission_mode", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@coding_type", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@modulation_type", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@fec_outer", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@code_rate_hp_stream", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@code_rate_lp_stream", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@hierarchy_information", MySqlDbType.Int32);
                mySqlCommand.Parameters.Add("@mpe_fec_indicator", MySqlDbType.Bool);
                mySqlCommand.Parameters.Add("@priority", MySqlDbType.Bool);
                mySqlCommand.Parameters.Add("@time_slicing_indicator", MySqlDbType.Bool);
                mySqlCommand.Parameters.Add("@network_name", MySqlDbType.VarChar);
                mySqlCommand.Parameters.Add("@target_region_country_code", MySqlDbType.VarChar);
                mySqlCommand.Parameters.Add("@uuid", MySqlDbType.VarChar);
                mySqlCommand.Parameters["@nid"].Value = networkId;
                mySqlCommand.Parameters["@tsid"].Value = transportStream.TransportStreamId;
                mySqlCommand.Parameters["@onid"].Value = transportStream.OriginalNetworkId;
                mySqlCommand.Parameters["@delivery_method"].Value = (int?)transportStream.DeliveryMethod;
                mySqlCommand.Parameters["@east"].Value = transportStream.East;
                mySqlCommand.Parameters["@fec_inner"].Value = (int?)transportStream.FecInner;
                mySqlCommand.Parameters["@frequency"].Value = transportStream.Frequency;
                mySqlCommand.Parameters["@orbital_position"].Value = transportStream.OrbitalPosition;
                mySqlCommand.Parameters["@polarization"].Value = (int?)transportStream.Polarization;
                mySqlCommand.Parameters["@roll_off"].Value = transportStream.RollOff;
                mySqlCommand.Parameters["@s2"].Value = transportStream.S2;
                mySqlCommand.Parameters["@symbol_rate"].Value = transportStream.SymbolRate;
                mySqlCommand.Parameters["@scrambling_sequence_index"].Value = transportStream.ScramblingSequenceIndex;
                mySqlCommand.Parameters["@input_stream_identifier"].Value = transportStream.InputStreamIdentifier;
                mySqlCommand.Parameters["@timeslice_number"].Value = transportStream.TimesliceNumber;
                mySqlCommand.Parameters["@ts_gs_mode"].Value = (int?)transportStream.TsGsMode;
                mySqlCommand.Parameters["@private_data_specifier_id"].Value = transportStream.PrivateDataSpecifierId;
                mySqlCommand.Parameters["@tfs_flag"].Value = transportStream.TfsFlag;
                mySqlCommand.Parameters["@bandwidth"].Value = transportStream.Bandwidth;
                mySqlCommand.Parameters["@guard_interval"].Value = transportStream.GuardInterval;
                mySqlCommand.Parameters["@other_frequency_flag"].Value = transportStream.OtherFrequencyFlag;
                mySqlCommand.Parameters["@plp_id"].Value = transportStream.PlpId;
                mySqlCommand.Parameters["@siso_miso"].Value = transportStream.SisoMiso;
                mySqlCommand.Parameters["@t2_system_id"].Value = transportStream.T2SystemId;
                mySqlCommand.Parameters["@transmission_mode"].Value = transportStream.TransmissionMode;
                mySqlCommand.Parameters["@coding_type"].Value = (int?)transportStream.CodingType;
                mySqlCommand.Parameters["@modulation_type"].Value = transportStream.ModulationType;
                mySqlCommand.Parameters["@fec_outer"].Value = (int?)transportStream.FecOuter;
                mySqlCommand.Parameters["@code_rate_hp_stream"].Value = (int?)transportStream.CodeRateHpStream;
                mySqlCommand.Parameters["@code_rate_lp_stream"].Value = (int?)transportStream.CodeRateLpStream;
                mySqlCommand.Parameters["@hierarchy_information"].Value = (int?)transportStream.HierarchyInformation;
                mySqlCommand.Parameters["@mpe_fec_indicator"].Value = transportStream.MpeFecIndicator;
                mySqlCommand.Parameters["@priority"].Value = transportStream.Priority;
                mySqlCommand.Parameters["@time_slicing_indicator"].Value = transportStream.TimeSlicingIndicator;
                mySqlCommand.Parameters["@network_name"].Value = transportStream.NetworkName;
                mySqlCommand.Parameters["@target_region_country_code"].Value = transportStream.TargetRegionCountryCode;
                if (hasLinkages)
                    mySqlCommand.Parameters["@uuid"].Value = uuid.ToString();
                else
                    mySqlCommand.Parameters["@uuid"].Value = DBNull.Value;
                SetNulls(mySqlCommand);
                mySqlCommand.ExecuteNonQuery();

                InsertNitTransportStreamCellFrequencies(connection, networkId, transportStream);
                InsertNitTransportStreamCellInfos(connection, networkId, transportStream);
                InsertNitTransportStreamCells(connection, networkId, transportStream);
                InsertNitTransportStreamCentreFrequencies(connection, networkId, transportStream);
                InsertNitTransportStreamServices(connection, networkId, transportStream, transaction);
                InsertNitTransportStreamTargetRegions(connection, networkId, transportStream);
                transaction.Commit();
            }

        }

        private void InsertBatTs(MySqlConnection connection, ushort batBouquetBouquetId, BatTransportStream child)
        {
            MySqlTransaction transaction = connection.BeginTransaction();
            MySqlCommand command = connection.CreateCommand();
            command.Transaction = transaction;
            command.CommandText =
                "INSERT INTO dvb_bat_transport_stream (bouquet_id, original_network_id, transport_stream_id, private_data_specifier, default_authority) " +
                "VALUES (@bouquet_id, @original_network_id, @transport_stream_id, @private_data_specifier, @default_authority)";
            command.Parameters.AddWithValue("@bouquet_id", batBouquetBouquetId);
            command.Parameters.AddWithValue("@original_network_id", child.OriginalNetworkId);
            command.Parameters.AddWithValue("@transport_stream_id", child.TransportStreamId);
            command.Parameters.AddWithValue("@private_data_specifier", child.PrivateDataSpecifier);
            command.Parameters.AddWithValue("@default_authority", child.DefaultAuthority);
            command.ExecuteNonQuery();

            InsertBatTransportStreamCountryAvailability(transaction, batBouquetBouquetId, child);
            InsertBatTransportStreamServiceList(transaction, batBouquetBouquetId, child);
            transaction.Commit();
        }

        private void InsertCat(MySqlConnection connection, int currentNetworkId, int currentTransportStreamId, CaDescriptor caDescriptor)
        {
            MySqlCommand mySqlCommand = connection.CreateCommand();
            mySqlCommand.CommandText =
                "INSERT INTO dvb_cat (nid, tsid, ca_pid, ca_system_id, private_data) VALUES (@nid,@tsid,@ca_pid,@ca_system_id,@private_data)";
            mySqlCommand.Parameters.Add("@nid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@tsid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@ca_pid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@ca_system_id", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@private_data", MySqlDbType.TinyBlob);
            mySqlCommand.Parameters["@nid"].Value = currentNetworkId;
            mySqlCommand.Parameters["@tsid"].Value = currentTransportStreamId;
            mySqlCommand.Parameters["@ca_pid"].Value = caDescriptor.CaPid;
            mySqlCommand.Parameters["@ca_system_id"].Value = caDescriptor.CaSystemId;
            if (caDescriptor.PrivateData == null)
                mySqlCommand.Parameters["@private_data"].Value = DBNull.Value;
            else if (caDescriptor.PrivateData.Length == 0)
                mySqlCommand.Parameters["@private_data"].Value = DBNull.Value;
            else
                mySqlCommand.Parameters["@private_data"].Value = caDescriptor.PrivateData;
            SetNulls(mySqlCommand);
            mySqlCommand.ExecuteNonQuery();
        }

        private void InsertSdt(MySqlConnection connection, ushort transportStreamId, ushort originalNetworkId, SdtService sdtService)
        {
            bool hasLinkages = HasLinkages(sdtService.Linkages);
            Guid linkageGuid = Guid.Empty;
            if (hasLinkages)
                linkageGuid = Guid.NewGuid();
            
                using (MySqlTransaction transaction = connection.BeginTransaction())
                {
                    using (MySqlCommand mySqlCommand = connection.CreateCommand())
                    {
                        mySqlCommand.Transaction = transaction;
                        mySqlCommand.CommandText =
                            "INSERT INTO dvb_sdt" +
                            "    (tsid, onid, service_id, eit_schedule, eit_schedule_following, running_status, free_ca_mode, service_name, service_provider_name, service_type, private_data_specifier, iso_639_language_code, text, data_broadcast_id, selector, reference_service_id, control_remote_access_over_internet, do_not_apply_revocation, do_not_scramble, uuid)" +
                            "VALUES" +
                            "    (@tsid,@onid,@service_id,@eit_schedule,@eit_schedule_following, @running_status, @free_ca_mode,@service_name,@service_provider_name,@service_type,@private_data_specifier,@iso_639_language_code,@text,@data_broadcat_id,@selector, @reference_service_id, @control_remote_access_over_internet, @do_not_apply_revocation, @do_not_scramble, @uuid)";
                        mySqlCommand.Parameters.Add("@tsid", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@onid", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@service_id", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@eit_schedule", MySqlDbType.Bool);
                        mySqlCommand.Parameters.Add("@eit_schedule_following", MySqlDbType.Bool);
                        mySqlCommand.Parameters.Add("@running_status", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@free_ca_mode", MySqlDbType.Bool);
                        mySqlCommand.Parameters.Add("@service_name", MySqlDbType.VarChar);
                        mySqlCommand.Parameters.Add("@service_provider_name", MySqlDbType.VarChar);
                        mySqlCommand.Parameters.Add("@service_type", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@private_data_specifier", MySqlDbType.Int64);
                        mySqlCommand.Parameters.Add("@component_tag", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@iso_639_language_code", MySqlDbType.VarChar);
                        mySqlCommand.Parameters.Add("@text", MySqlDbType.VarChar);
                        mySqlCommand.Parameters.Add("@data_broadcat_id", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@selector", MySqlDbType.TinyBlob);
                        mySqlCommand.Parameters.Add("@reference_service_id", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@control_remote_access_over_internet", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@do_not_apply_revocation", MySqlDbType.Bool);
                        mySqlCommand.Parameters.Add("@do_not_scramble", MySqlDbType.Bool);
                        mySqlCommand.Parameters.Add("@old_onid", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@old_service_id", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@old_tsid", MySqlDbType.Int32);
                        mySqlCommand.Parameters.Add("@uuid", MySqlDbType.VarChar);
                        mySqlCommand.Parameters["@tsid"].Value = transportStreamId;
                        mySqlCommand.Parameters["@onid"].Value = originalNetworkId;
                        mySqlCommand.Parameters["@service_id"].Value = sdtService.ServiceId;
                        mySqlCommand.Parameters["@eit_schedule"].Value = sdtService.EitScheduleFlag;
                        mySqlCommand.Parameters["@eit_schedule_following"].Value = sdtService.EitPresentFollowingFlag;
                        mySqlCommand.Parameters["@running_status"].Value = (int)sdtService.RunningStatus;
                        mySqlCommand.Parameters["@free_ca_mode"].Value = sdtService.FreeCaMode;
                        mySqlCommand.Parameters["@service_name"].Value = sdtService.ServiceName;
                        mySqlCommand.Parameters["@service_provider_name"].Value = sdtService.ServiceProviderName;
                        mySqlCommand.Parameters["@service_type"].Value = (int?)sdtService.ServiceType;
                        mySqlCommand.Parameters["@private_data_specifier"].Value = sdtService.PrivateDataSpecifier;
                        mySqlCommand.Parameters["@component_tag"].Value = sdtService.ComponentTag;
                        mySqlCommand.Parameters["@iso_639_language_code"].Value = sdtService.Iso639LanguageCode;
                        mySqlCommand.Parameters["@text"].Value = sdtService.Text;
                        mySqlCommand.Parameters["@data_broadcat_id"].Value = sdtService.DataBroadcastId;
                        mySqlCommand.Parameters["@selector"].Value = sdtService.Selector;
                        mySqlCommand.Parameters["@reference_service_id"].Value = sdtService.ReferenceServiceId;
                        mySqlCommand.Parameters["@control_remote_access_over_internet"].Value = sdtService.ControlRemoteAccessOverInternet;
                        mySqlCommand.Parameters["@do_not_apply_revocation"].Value = sdtService.DoNotApplyRevocation;
                        mySqlCommand.Parameters["@do_not_scramble"].Value = sdtService.DoNotScramble;
                        mySqlCommand.Parameters["@old_onid"].Value = sdtService.OldOriginalNetworkId;
                        mySqlCommand.Parameters["@old_service_id"].Value = sdtService.OldServiceId;
                        mySqlCommand.Parameters["@old_tsid"].Value = sdtService.OldTransportStreamId;
                        mySqlCommand.Parameters["@uuid"].Value = hasLinkages ? linkageGuid : null;
                        SetNulls(mySqlCommand);
                        mySqlCommand.ExecuteNonQuery();
                    }

                    InsertSdtCaIdentifiers(transaction, transportStreamId, originalNetworkId, sdtService);
                    InsertSdtCountryAvailability(transaction, transportStreamId, originalNetworkId, sdtService);
                    if (hasLinkages)
                        InsertSdtLinkages(connection, linkageGuid, sdtService.Linkages, transaction);
                    InsertSdtMultilingualServiceName(connection, transportStreamId, originalNetworkId, sdtService);
                    InsertSdtNvodReferences(transaction, transportStreamId, originalNetworkId, sdtService);
                    InsertSdtComponents(transaction, transportStreamId, originalNetworkId, sdtService);
                    transaction.Commit();
                }

        }

        private void UpdateTsdtStationIdentification(MySqlConnection connection, int cnid, int ctsid, string stationIdentification)
        {
            MySqlCommand command = connection.CreateCommand();
            command.CommandText =
                "UPDATE dvb_tsdt SET station_identification = @stationIdent WHERE cnid = @cnid AND @ctsid = @ctsid";
            command.Parameters.AddWithValue("@stationIdent", stationIdentification);
            command.Parameters.AddWithValue("@cnid", cnid);
            command.Parameters.AddWithValue("@ctsid", ctsid);
            command.ExecuteNonQuery();
        }

        private void InsertTsdt(MySqlConnection connection, TsdtCoordinate tsdtCoordinate)
        {
            MySqlCommand command = connection.CreateCommand();
            command.CommandText = "INSERT INTO dvb_tsdt (cnid, ctsid, compliance) VALUES (@cnid,@ctsid,@compliance)";
            command.Parameters.AddWithValue("@cnid", tsdtCoordinate.CurrentNetworkId);
            command.Parameters.AddWithValue("@ctsid", tsdtCoordinate.CurrentTransportStreamId);
            command.Parameters.AddWithValue("@compliance", tsdtCoordinate.Compliance);
            command.ExecuteNonQuery();
        }

        private void InsertPmt(MySqlConnection connection, int currentNetworkId, int currentTransportStreamId, ProgramMapping mapping)
        {
            /*MySqlCommand mySqlCommand = connection.CreateCommand();
            mySqlCommand.CommandText =
                "SELECT dateadded FROM dvb_pmt WHERE nid = @nid AND tsid = @tsid AND program_number = @program_number";
            mySqlCommand.Parameters.Add("@nid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@tsid", MySqlDbType.Int32);
            mySqlCommand.Parameters.Add("@program_number", MySqlDbType.Int32);
            mySqlCommand.Parameters["@nid"].Value = currentNetworkId;
            mySqlCommand.Parameters["@tsid"].Value = currentTransportStreamId;
            mySqlCommand.Parameters["@program_number"].Value = mapping.ProgramNumber;
            MySqlDataReader dataReader = mySqlCommand.ExecuteReader();
            bool alreadyKnown = dataReader.Read();
            dataReader.Close();
            if (alreadyKnown)
                return;*/

            MySqlTransaction transaction = connection.BeginTransaction();
            MySqlCommand mySqlCommand = connection.CreateCommand();
            mySqlCommand.Transaction = transaction;
            mySqlCommand.CommandText =
                "INSERT INTO dvb_pmt " +
                "(nid, tsid, program_number, pcr_pid, maximum_bitrate, multiplex_buffer_utilization_bound_valid_flag, multiplex_lfw_offset_lower_bound, multiplex_ltw_offset_upper_bound, clock_accuracy_exponent, clock_accuracy_integer, external_clock_reference_indicator, sb_leak_rate, sb_size, ca_pid, ca_system_id, ca_private_data, private_data_specifier, registration_additional_identification_info, registration_format_identifier, new_original_network_id, new_service_id, new_transport_stream_id, component_tag, metadata_input_leak_rate, metadata_buffer_size, metadata_output_leak_rate, scrambling_mode, es_id, audio_type, iso_639_language_code, iod_graphics_profile_level_indication, iod_visual_profile_level_indication, iod_audio_profile_level_indication, iod_scene_profile_level_indication, iod_od_profile_level_indication, iod_url_string, iod_include_inline_profile_level_flag, iod_url_flag, iod_object_descriptor_id, scope_of_iod_label, iod_label, private_data_indicator, frame_Rate, chroma_format, constrained_parameter_flag, frame_rate_extension_flag, mpeg1_only_flag, multiple_framerate_flag, profile_and_level_indication, still_picture_flag, metadata_program_number, metadata_application_format, metadata_application_format_identifier, metadata_format, metadata_format_identifier, metadata_locator_record, metadata_locator_record_flag, metadata_service_id, mpeg_carriage_flag, metadata_private_data, transport_stream_id, transport_stream_location, free_format, audio_stream_id, layer, variable_rate_audio, copy_control_private_data, alignment_type, hierarchy_type, hierarchy_layer_type, tref_present_flag, hierarchy_channel, no_view_scalability_flag, hierarchy_embedded_layer_index, no_quality_scalability_flag, no_spatial_scalability_flag, no_temporal_scalability_flag) " +
                "VALUES " +
                "(@nid, @tsid, @program_number, @pcr_pid, @maximum_bitrate, @multiplex_buffer_utilization_bound_valid_flag, @multiplex_lfw_offset_lower_bound, @multiplex_ltw_offset_upper_bound, " +
                "@clock_accuracy_exponent, @clock_accuracy_integer, @external_clock_reference_indicator, @sb_leak_rate, @sb_size, @ca_pid, @ca_system_id, @ca_private_data, @private_data_specifier, " +
                "@registration_additional_identification_info, @registration_format_identifier, @new_original_network_id, @new_service_id, @new_transport_stream_id, @component_tag, " +
                "@metadata_input_leak_rate, @metadata_buffer_size, @metadata_output_leak_rate, @scrambling_mode, @es_id, @audio_type, @iso_639_language_code, @iod_graphics_profile_level_indication, " +
                "@iod_visual_profile_level_indication, @iod_audio_profile_level_indication, @iod_scene_profile_level_indication, @iod_od_profile_level_indication, @iod_url_string, " +
                "@iod_include_inline_profile_level_flag, @iod_url_flag, @iod_object_descriptor_id, @scope_of_iod_label, @iod_label, @private_data_indicator, @frame_Rate, @chroma_format, @constrained_parameter_flag, @frame_rate_extension_flag, @mpeg1_only_flag, @multiple_framerate_flag, @profile_and_level_indication, @still_picture_flag, @metadata_program_number, @metadata_application_format, @metadata_application_format_identifier, @metadata_format, @metadata_format_identifier, @metadata_locator_record, @metadata_locator_record_flag, @metadata_service_id, @mpeg_carriage_flag, @metadata_private_data, @transport_stream_id, @transport_stream_location, @free_format, @audio_stream_id, @layer, @variable_rate_audio, @copy_control_private_data, @alignment_type, @hierarchy_type, @hierarchy_layer_type, @tref_present_flag, @hierarchy_channel, @no_view_scalability_flag, @hierarchy_embedded_layer_index, @no_quality_scalability_flag, @no_spatial_scalability_flag, @no_temporal_scalability_flag)\r\n";
            mySqlCommand.Parameters.AddWithValue("@nid", currentNetworkId);
            mySqlCommand.Parameters.AddWithValue("@tsid", currentTransportStreamId);
            mySqlCommand.Parameters.AddWithValue("@program_number", mapping.ProgramNumber);
            mySqlCommand.Parameters.AddWithValue("@pcr_pid", mapping.PcrPid);
            mySqlCommand.Parameters.AddWithValue("@maximum_bitrate", mapping.MaximumBitrate);
            mySqlCommand.Parameters.AddWithValue("@multiplex_buffer_utilization_bound_valid_flag", mapping.MultiplexBufferUtilizationBoundValidFlag);
            mySqlCommand.Parameters.AddWithValue("@multiplex_lfw_offset_lower_bound", mapping.MultiplexLtwOffsetLowerBound);
            mySqlCommand.Parameters.AddWithValue("@multiplex_ltw_offset_upper_bound", mapping.MultiplexLtwOffsetUpperBound);
            mySqlCommand.Parameters.AddWithValue("@clock_accuracy_exponent", mapping.ClockAccuracyExponent);
            mySqlCommand.Parameters.AddWithValue("@clock_accuracy_integer", mapping.ClockAccuracyInteger);
            mySqlCommand.Parameters.AddWithValue("@external_clock_reference_indicator", mapping.ExternalClockReferenceIndicator);
            mySqlCommand.Parameters.AddWithValue("@sb_leak_rate", mapping.SbLeakRate);
            mySqlCommand.Parameters.AddWithValue("@sb_size", mapping.SbSize);
            mySqlCommand.Parameters.AddWithValue("@ca_pid", mapping.CaPid);
            mySqlCommand.Parameters.AddWithValue("@ca_system_id", mapping.CaSystemId);
            mySqlCommand.Parameters.AddWithValue("@ca_private_data", mapping.CaPrivateData);
            mySqlCommand.Parameters.AddWithValue("@private_data_specifier", mapping.PrivateDataSpecifier);
            mySqlCommand.Parameters.AddWithValue("@registration_additional_identification_info", mapping.RegistrationAdditionalIdentificationInfo);
            mySqlCommand.Parameters.AddWithValue("@registration_format_identifier", mapping.RegistrationFormatIdentifier);
            mySqlCommand.Parameters.AddWithValue("@new_original_network_id", mapping.NewOriginalNetworkId);
            mySqlCommand.Parameters.AddWithValue("@new_service_id", mapping.NewServiceId);
            mySqlCommand.Parameters.AddWithValue("@new_transport_stream_id", mapping.NewTransportStreamId);
            mySqlCommand.Parameters.AddWithValue("@component_tag", mapping.ComponentTag);
            mySqlCommand.Parameters.AddWithValue("@metadata_input_leak_rate", mapping.MetadataInputLeakRate);
            mySqlCommand.Parameters.AddWithValue("@metadata_buffer_size", mapping.MetadataBufferSize);
            mySqlCommand.Parameters.AddWithValue("@metadata_output_leak_rate", mapping.MetadataOutputLeakRate);
            mySqlCommand.Parameters.AddWithValue("@scrambling_mode", mapping.ScramblingMode);
            mySqlCommand.Parameters.AddWithValue("@es_id", mapping.EsId);
            mySqlCommand.Parameters.AddWithValue("@audio_type", mapping.AudioType);
            mySqlCommand.Parameters.AddWithValue("@iso_639_language_code", mapping.Iso639LanguageCode);
            if (mapping.InitialObjectDescriptor != null)
            {
                mySqlCommand.Parameters.AddWithValue("@iod_graphics_profile_level_indication", mapping.InitialObjectDescriptor.GraphicsProfileLevelIndication);
                mySqlCommand.Parameters.AddWithValue("@iod_visual_profile_level_indication", mapping.InitialObjectDescriptor.VisualProfileLevelIndication);
                mySqlCommand.Parameters.AddWithValue("@iod_audio_profile_level_indication", mapping.InitialObjectDescriptor.AudioProfileLevelIndication);
                mySqlCommand.Parameters.AddWithValue("@iod_scene_profile_level_indication", mapping.InitialObjectDescriptor.SceneProfileLevelIndication);
                mySqlCommand.Parameters.AddWithValue("@iod_od_profile_level_indication", mapping.InitialObjectDescriptor.OdProfileLevelIndication);
                mySqlCommand.Parameters.AddWithValue("@iod_url_string", mapping.InitialObjectDescriptor.UrlString);
                mySqlCommand.Parameters.AddWithValue("@iod_include_inline_profile_level_flag", mapping.InitialObjectDescriptor.IncludeInlineProfileLevelFlag);
                mySqlCommand.Parameters.AddWithValue("@iod_url_flag", mapping.InitialObjectDescriptor.UrlFlag);
                mySqlCommand.Parameters.AddWithValue("@iod_object_descriptor_id", mapping.InitialObjectDescriptor.ObjectDescriptorId);
            }
            else
            {
                mySqlCommand.Parameters.AddWithValue("@iod_graphics_profile_level_indication", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_visual_profile_level_indication", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_audio_profile_level_indication", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_scene_profile_level_indication", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_od_profile_level_indication", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_url_string", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_include_inline_profile_level_flag", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_url_flag", DBNull.Value);
                mySqlCommand.Parameters.AddWithValue("@iod_object_descriptor_id", DBNull.Value);
            }
            //@, @, @, @, @)\r\n";
            mySqlCommand.Parameters.AddWithValue("@scope_of_iod_label", mapping.ScopeOfIodLabel);
            mySqlCommand.Parameters.AddWithValue("@iod_label", mapping.IodLabel);
            mySqlCommand.Parameters.AddWithValue("@private_data_indicator", mapping.PrivateDataIndicator);
            mySqlCommand.Parameters.AddWithValue("@frame_Rate", mapping.FrameRate);
            mySqlCommand.Parameters.AddWithValue("@chroma_format", mapping.ChromaFormat);
            mySqlCommand.Parameters.AddWithValue("@constrained_parameter_flag", mapping.ConstrainedParameterFlag);
            mySqlCommand.Parameters.AddWithValue("@frame_rate_extension_flag", mapping.FrameRateExtensionFlag);
            mySqlCommand.Parameters.AddWithValue("@mpeg1_only_flag", mapping.Mpeg1OnlyFlag);
            mySqlCommand.Parameters.AddWithValue("@multiple_framerate_flag", mapping.MultipleFramerateFlag);
            mySqlCommand.Parameters.AddWithValue("@profile_and_level_indication", mapping.ProfileAndLevelIndication);
            mySqlCommand.Parameters.AddWithValue("@still_picture_flag", mapping.StillPictureFlag);
            mySqlCommand.Parameters.AddWithValue("@metadata_program_number", mapping.MetadataProgramNumber);
            mySqlCommand.Parameters.AddWithValue("@metadata_application_format", mapping.MetadataApplicationFormat);
            mySqlCommand.Parameters.AddWithValue("@metadata_application_format_identifier", mapping.MetadataApplicationFormatIdentifier);
            mySqlCommand.Parameters.AddWithValue("@metadata_format", mapping.MetadataFormat);
            mySqlCommand.Parameters.AddWithValue("@metadata_format_identifier", mapping.MetadataFormatIdentifier);
            mySqlCommand.Parameters.AddWithValue("@metadata_locator_record", mapping.MetadataLocatorRecord);
            mySqlCommand.Parameters.AddWithValue("@metadata_locator_record_flag", mapping.MetadataLocatorRecordFlag);
            mySqlCommand.Parameters.AddWithValue("@metadata_service_id", mapping.MetadataServiceId);
            mySqlCommand.Parameters.AddWithValue("@mpeg_carriage_flag", mapping.MpegCarriageFlag);
            mySqlCommand.Parameters.AddWithValue("@metadata_private_data", mapping.MetadataPrivateData);
            mySqlCommand.Parameters.AddWithValue("@transport_stream_id", mapping.TransportStreamId);
            mySqlCommand.Parameters.AddWithValue("@transport_stream_location", mapping.TransportStreamLocation);
            mySqlCommand.Parameters.AddWithValue("@free_format", mapping.FreeFormat);
            mySqlCommand.Parameters.AddWithValue("@audio_stream_id", mapping.AudioStreamId);
            mySqlCommand.Parameters.AddWithValue("@layer", mapping.Layer);
            mySqlCommand.Parameters.AddWithValue("@variable_rate_audio", mapping.VariableRateAudio);
            mySqlCommand.Parameters.AddWithValue("@copy_control_private_data", mapping.CopyControlPrivateData);
            mySqlCommand.Parameters.AddWithValue("@alignment_type", mapping.AlignmentType);
            mySqlCommand.Parameters.AddWithValue("@hierarchy_type", mapping.HierarchyType);
            mySqlCommand.Parameters.AddWithValue("@hierarchy_layer_type", mapping.HierarchyLayerType);
            mySqlCommand.Parameters.AddWithValue("@tref_present_flag", mapping.TrefPresentFlag);
            mySqlCommand.Parameters.AddWithValue("@hierarchy_channel", mapping.HierarchyChannel);
            mySqlCommand.Parameters.AddWithValue("@no_view_scalability_flag", mapping.NoViewScalabilityFlag);
            mySqlCommand.Parameters.AddWithValue("@hierarchy_embedded_layer_index", mapping.HierarchyEmbeddedLayerIndex);
            mySqlCommand.Parameters.AddWithValue("@no_quality_scalability_flag", mapping.NoQualityScalabilityFlag);
            mySqlCommand.Parameters.AddWithValue("@no_spatial_scalability_flag", mapping.NoSpatialScalabilityFlag);
            mySqlCommand.Parameters.AddWithValue("@no_temporal_scalability_flag", mapping.NoTemporalScalabilityFlag);
            SetNulls(mySqlCommand);
            int executeNonQuery = mySqlCommand.ExecuteNonQuery();

            if (executeNonQuery > 0)
            {
                InsertPmtStreams(connection, mapping, currentNetworkId, currentTransportStreamId, transaction);
            }

            transaction.Commit();
        }
    }
}
