using System;
using System.Collections.Generic;
using System.Linq;
using MassTransit;
using MassTransit.Util;
using System.Data;
using Microsoft.Extensions.Configuration;
using Dapper;

namespace WK_KLI_LAPS_COMMONTOOL_Service.App_Data
{
    public class RabbitMq
    {
        public bool SendMq(string Tranid, string UserId, string AppType, string StageType, string Enviroment)
        {

            string ServiceAddress = "";
            string RabbitMQHost = "";
            string userName = "";
            string password = "";

            //  BLDatamanipulation db = new BLDatamanipulation();
            using (IDbConnection dbConnection = ConnectionBase.Connection)
            {
                dbConnection.Open();
                DynamicParameters param = new DynamicParameters();
                param.Add("p_tranid", dbType: DbType.Int32, value: Tranid, direction: ParameterDirection.Input);
                param.Add("p_lotid", dbType: DbType.Int32, value: UserId, direction: ParameterDirection.Input);
                param.Add("p_option", dbType: DbType.String, value: "P", direction: ParameterDirection.Input);
                param.Add("p_option", dbType: DbType.String, value: AppType, direction: ParameterDirection.Input);
                var Checkinapp = dbConnection.Query<object>("public.spusrlottranupdatev1", param, commandType: CommandType.StoredProcedure).ToList();

                //var Checkinapp = db.GetDataTable(db_, "select * from usr_lot_tran_update_v1(" + Tranid + ", " + UserId + ", '" + "P" + "', '" + AppType + "') as dd", null);

                //--uncomment and check start------
                //if (Checkinapp.Rows.Count > 0)
                //{
                //    for (var item = 0; item <= Checkinapp.Rows.Count - 1; item++)
                //    {
                //        checkinprocess obj = JsonConvert.DeserializeObject<checkinprocess>(Checkinapp.Rows[item][0].ToString());
                //        if (obj.ipaddress != null)
                //        {
                //            ServiceAddress = obj.ipaddress + "" + "/" + obj.root_path;
                //            RabbitMQHost = obj.ipaddress;
                //            userName = obj.username;
                //            password = obj.password;
                //            StageType = obj.stagetype;
                //        }
                //        else
                //        {
                //            return false;
                //        }
                //    }
                //}
                //--uncomment and check end------
                if (StageType != "server")
                    return false;

            }




            //ConfigureLogger();
            // Log4NetLogger.Use();
            IBusControl busControl = CreateBus(RabbitMQHost, userName, password);
            TaskUtil.Await(() => busControl.StartAsync());

            try
            {

                IRequestClient<ISimpleRequest, ISimpleResponse> client = CreateRequestClient(busControl, ServiceAddress);
                var response = client.Request(new SimpleRequest(DateTime.Now.ToString(), Tranid, UserId, AppType, StageType, Enviroment, null, ""));
                System.Threading.Thread.Sleep(500);
                //client = null;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {

                busControl.Stop();
            }
            return true;
        }

        public bool SendMqMail(string Tranid, string JobWorkflowid, string flag, string curtranid, string userid)
        {

            string ServiceAddress = "";
            string RabbitMQHost = "";
            string userName = "";
            string password = "";
           
            ServiceAddress = Startup.Configuration.GetValue<string>("AppSettings:mailqueue_path") + "" + "/" + Startup.Configuration.GetValue<string>("AppSettings:mailqueue");  //obj.ipaddress + "" + " /" + obj.root_path;
            RabbitMQHost = Startup.Configuration.GetValue<string>("AppSettings:mailqueue_path");  //obj.ipaddress;
            userName = "admin"; //obj.username;
            password = "admin"; //obj.password;

            //ConfigureLogger();
            // Log4NetLogger.Use();
            IBusControl busControl = CreateBus(RabbitMQHost, userName, password);
            TaskUtil.Await(() => busControl.StartAsync());

            try
            {
                //p.TransId => tranid
                //p.AppType => jobworkflowid
                //p.StageType => sflag
                //p.Enviroment => curtranid
                //p.UserId => userid_

                DynamicParams dynamicparams = new DynamicParams()
                {
                    jobworkflowid = JobWorkflowid,
                    nexttranid = curtranid
                };
                List<DynamicParams> dynamicparams_ = new List<DynamicParams>();
                dynamicparams_.Add(dynamicparams);
                IRequestClient<ISimpleRequest, ISimpleResponse> client = CreateRequestClient(busControl, ServiceAddress);
                var response = client.Request(new SimpleRequest(DateTime.Now.ToString(), Tranid, userid, "", "", Startup.Configuration.GetValue<string>("AppSettings:envirnmentname"), dynamicparams, flag));
                System.Threading.Thread.Sleep(500);
                //client = null;
            }
            catch (Exception ex)
            {
                return false;
            }
            finally
            {

                busControl.Stop();
            }
            return true;
        }

        public IRequestClient<ISimpleRequest, ISimpleResponse> CreateRequestClient(IBusControl busControl, string ServiceAddress)
        {
            var serviceAddress = new Uri(ServiceAddress);
            IRequestClient<ISimpleRequest, ISimpleResponse> client =
                busControl.CreateRequestClient<ISimpleRequest, ISimpleResponse>(serviceAddress, TimeSpan.FromSeconds(10));

            return client;
        }

        public IBusControl CreateBus(string RabbitMQHost, string userName, string password)
        {
            return Bus.Factory.CreateUsingRabbitMq(x => x.Host(new Uri(RabbitMQHost), h =>
            {
                h.Username(userName);
                h.Password(password);
            }));
        }

        static void ConfigureLogger()
        {
//            const string logConfig = @"<?xml version=""1.0"" encoding=""utf-8"" ?>
//<log4net>
//  <root>
//    <level value=""INFO"" />
//    <appender-ref ref=""console"" />
//  </root>
//  <appender name=""console"" type=""log4net.Appender.ColoredConsoleAppender"">
//    <layout type=""log4net.Layout.PatternLayout"">
//      <conversionPattern value=""%m%n"" />
//    </layout>
//  </appender>
//</log4net>";

//            using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(logConfig)))
//            {
//                XmlConfigurator.Configure(stream);
//            }
        }
    }

}
public interface ISimpleResponse
{
    string CusomerName { get; }
}
public interface ISimpleRequest
{
    DateTime Timestamp { get; }
    string CustomerId { get; }
    string TransId { get; set; }
    string UserId { get; set; }
    string AppType { get; set; }
    string StageType { get; set; }
    string Enviroment { get; set; }
    object DynamicList { get; set; }
    string Flag { get; set; }
}
class SimpleRequest
    : ISimpleRequest

{
    readonly string _customerId;
    readonly string _TransId;
    readonly string _UserId;
    readonly string _AppType;
    readonly string _StageType;
    readonly string _Enviroment;
    readonly DateTime _timestamp;
    readonly object _DynamicList;
    readonly string _Flag;

    public SimpleRequest(string customerId, string Tranid, string UserId, string AppType, string StageType, string Enviroment, object DynamicList, string Flag)
    {
        _customerId = customerId;
        _TransId = Tranid;
        _UserId = UserId;
        _AppType = AppType;
        _StageType = StageType;
        _Enviroment = Enviroment;
        _timestamp = DateTime.UtcNow;
        _DynamicList = DynamicList;
        _Flag = Flag;
    }

    public DateTime Timestamp
    {
        get { return _timestamp; }
    }
    public string TransId
    {
        get { return _TransId; }
    }
    public string CustomerId
    {
        get { return _customerId; }
    }
    public string UserId
    {
        get { return _UserId; }
    }
    public string AppType
    {
        get { return _AppType; }
    }
    public string StageType
    {
        get { return _StageType; }
    }
    public string Enviroment
    {
        get { return _Enviroment; }
    }
    public object DynamicList
    {
        get { return _DynamicList; }
    }
    public string Flag
    {
        get { return _Flag; }
    }



    string ISimpleRequest.TransId
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    string ISimpleRequest.UserId
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    string ISimpleRequest.AppType
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    string ISimpleRequest.StageType
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    string ISimpleRequest.Enviroment
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    object ISimpleRequest.DynamicList
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

    string ISimpleRequest.Flag
    {
        get
        {
            throw new NotImplementedException();
        }

        set
        {
            throw new NotImplementedException();
        }
    }

}

public class checkinprocess
{
    public Int32? jobworkflowid { get; set; }
    public Int32? isexe { get; set; }
    public Int32? isservice { get; set; }
    public Int32? applicationserverid { get; set; }
    public string paramss { get; set; }
    public string ipaddress { get; set; }
    public string appname { get; set; }
    public string stagetype { get; set; }
    public string file_movement { get; set; }
    public string root_path { get; set; }
    public Int32? stageorder { get; set; }
    public string checkout_app { get; set; }
    public Int32? appid { get; set; }
    public string username { get; set; }
    public string password { get; set; }
}

public class DynamicParams
{
    public string jobworkflowid { get; set; }
    public string nexttranid { get; set; }
}
