using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Xml;
using System.IO;
using TM.Shared.Components;

namespace TM.Bosman.Components
{
    public class MSsql
    {
        public static string AddReference(string reference)
        {
            // Possible results: "Added", "Already exists", "Error!", "Unexpected result!"
            string result = "Unexpected result!";

            string creation = DateTimeFunctions.GetCurrentDateTime();

            OleDbConnection ESBLookups = new OleDbConnection(SSOFunctions.GetValue("TM.Bosman", "ESBLookupConnectionString2016"));
            try
            {
                ESBLookups.Open();
                OleDbCommand sqlCommand = ESBLookups.CreateCommand();
                sqlCommand.CommandText = "select count(*) COUNT from TM_Bosman_Reference where reference = '" + reference.Trim() + "'";
                OleDbDataReader reader = sqlCommand.ExecuteReader();
                while (reader.Read())
                {
                    if (Convert.ToInt32(reader["COUNT"].ToString()) > 0)
                    {
                        result = "Already exists";
                    }
                    else
                    {
                        result = "Not found";
                    }
                }
                reader.Close();
                if (result == "Not found")
                {
                    sqlCommand.CommandText = "INSERT INTO TM_Bosman_Reference (Reference, DateTime) VALUES ('" + reference.Trim() + "', '" + creation.ToString() + "')";
                    reader = sqlCommand.ExecuteReader();
                    result = "Added";
                }
                reader.Close();
            }
            catch (Exception ex) { throw ex; result = "Error!"; }
            finally { ESBLookups.Close(); }
            return result;
        }

        public static string CheckReference(string reference)
        {
            // Possible results: "Found", "Not Found", "Error!", "Unexpected result!"
            string result = "Unexpected result!";
            OleDbConnection ESBLookups = new OleDbConnection(SSOFunctions.GetValue("TM.Bosman", "ESBLookupConnectionString2016"));
            try
            {
                ESBLookups.Open();
                OleDbCommand sqlCommand = ESBLookups.CreateCommand();
                sqlCommand.CommandText = "select count(*) COUNT from TM_Bosman_Reference where reference = '" + reference.Trim() + "'";
                OleDbDataReader reader = sqlCommand.ExecuteReader();
                while (reader.Read())
                {
                    if (Convert.ToInt32(reader["COUNT"].ToString()) > 0)
                    {
                        result = "Final"; // = "Found"
                    }
                    else
                    {
                        result = "New"; // = Not Found"
                    }
                }
            }
            catch (Exception ex) { throw ex; result = "Error!"; }
            finally { ESBLookups.Close(); }
            return result;
        }
    }

    public class Ixolution
    {
        // Oorspronkelijk Biztalk opzet werden referenties in de Ixolution TMS Oracle database gechecked.
        // In de nieuwe opzet 'mag dat niet meer' en wordt een eigen administratie met MS SQL Server opgezet.

        public static string WimBosman_checkPreAdvicesAndFinals(XmlDocument doc)
        {
            // Check the references that are sent if they are already in the system at venlo or eersel to identfy new or finals in the e-mail header!
            OleDbConnection OracleConnectionVenlo = new OleDbConnection(@"File Name='c:\Program Files\Common Files\KLG\KLG_TMS_ORACLE.udl';");
            OleDbConnection OracleConnectionEersel = new OleDbConnection(@"File Name='c:\Program Files\Common Files\KLG\KLG_TMS_ORACLE_EERSEL.udl';");

            string receiver = doc.SelectSingleNode("//*[local-name()='OrdersIntern']/*[local-name()='Header']/*[local-name()='Receiver']").InnerText;
            List<string> references = new List<string>();
            XmlNodeList nodes = doc.SelectNodes("//*[local-name()='ShipmentFields']");

            int preAdvices = 0;
            int finals = 0;

            foreach (XmlNode node in nodes)
            {
                // Check existense in iXolution Venlo
                if (receiver == "KLGNLVEN")
                {
                    try
                    {
                        OracleConnectionVenlo.Open();
                        OleDbCommand OracleCommand = OracleConnectionVenlo.CreateCommand();
                        OracleCommand.CommandText = "SELECT COUNT(*) CTR FROM TMS.SHIPMENT WHERE REFERENCE = '" + node.SelectSingleNode("*[local-name()='ClientReference']").InnerText + "' AND CONSIGNOR_COMPANY_CODE = 'BOSMASHEER01'";
                        OleDbDataReader OracleReader = OracleCommand.ExecuteReader();
                        while (OracleReader.Read())
                        {
                            if (Convert.ToInt32(OracleReader["CTR"].ToString()) > 0)
                            {
                                finals = finals + 1;
                            }
                            else
                            {
                                preAdvices = preAdvices + 1;
                            }
                        }
                    }
                    catch (Exception ex) { throw ex; }
                    finally { OracleConnectionVenlo.Close(); }

                    OracleConnectionVenlo.Close();
                }

                else if (receiver == "KLGNLEER")
                {
                    // Check existense in iXolution Venlo
                    try
                    {
                        OracleConnectionEersel.Open();
                        OleDbCommand OracleCommand = OracleConnectionEersel.CreateCommand();
                        OracleCommand.CommandText = "SELECT COUNT(*) CTR FROM TMS.SHIPMENT WHERE REFERENCE = '" + node.SelectSingleNode("//*[local-name()='Shipment']/*[local-name()='ShipmentFields']/*[local-name()='ClientReference']").InnerText + "' AND CONSIGNOR_COMPANY_CODE = 'WIMBOSHEER01'";
                        OleDbDataReader OracleReader = OracleCommand.ExecuteReader();
                        while (OracleReader.Read())
                        {
                            if (Convert.ToInt32(OracleReader["CTR"].ToString()) > 0)
                            {
                                finals = finals + 1;
                            }
                            else
                            {
                                preAdvices = preAdvices + 1;
                            }
                        }
                    }
                    catch (Exception ex) { throw ex; }
                    finally { OracleConnectionEersel.Close(); }

                    OracleConnectionEersel.Close();
                }
                else
                {
                    string message = "Receiver is not KLGNLVEN or KLGNLEER!";
                    throw new Exception(message, new Exception(doc.InnerXml));
                }
            }

            if (nodes.Count != (preAdvices + finals))
            {
                string message = "Total count in xml (" + nodes.Count + ") for preAdvices (" + preAdvices + ") and finals (" + finals + ") in this message did not meet eachoter, see innerexception for used the message\r probably there was a connection error with the check in iXolution?";

                throw new Exception(message, new Exception(doc.InnerXml));
            }

            return " (" + preAdvices + " new, " + finals + " finals)";
        }


    }

    public class Logging
    {
        public static void WriteToLog(String Message)
        {
            StreamWriter writeText = new StreamWriter("D:\\SVN\\EDI\\KLG.BizTalk\\TM\\Bosman\\Transforms.Test\\Logging\\LogBosman.txt", append: true);
            writeText.WriteLine(Message);
            writeText.Close();
        }
    }
}
