using betrace_carfi_erp_driver.Common;
using betrace_carfi_erp_driver.Primavera10.Engine;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using Serilog;
using Serilog.Events;
using Newtonsoft.Json;
using System.IO;
namespace betrace_carfi_erp_driver
{
    public partial class ERPService : Form
    {
        

        System.Timers.Timer timer = new System.Timers.Timer();
        bool stop = true;

        public ERPService()
        {
            InitializeComponent();

            //Log Desenvolvimento 
string path =  "c:\\BeTrace_DriverERP_Log_DEV\\" ;
           
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            if (!path.EndsWith("\\"))
                path = path + "\\";
            string logFile = path + DateTime.Now.ToString("yyyyMMdd") + ".txt";
           
            Log.Logger = new LoggerConfiguration()
          .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
          .Enrich.FromLogContext()
          .WriteTo.Console()
          .WriteTo.File(logFile )
          .CreateLogger();
           
 //TopMost = true;
            btnStart.Enabled = false;
            btnStopDriver.Enabled = false;
            Logger.WriteEntry("Initializing ERP Service.", EventLogEntryType.Information);

            // Set up a timer that triggers every 15 seconds.
            timer.Interval = (15 * 1000); 
            timer.Elapsed += new ElapsedEventHandler(this.timer_Tick);

            btnStart.Enabled = true;

            if (!SystemInfo.ReloadSystemInfo()) StopDriver();

            lblVersion.Text = "Version: " + Assembly.GetExecutingAssembly().GetName().Version.ToString();
        }

        #region "Methods"

        private void StartDriver()
        {
            switch (SystemInfo.ERP_Type.ToUpper())
            {
                case "PRIMAVERA10":
                    try
                    {
                        PriEngine.CreatContext(SystemInfo.ERP_Enterprise, SystemInfo.ERP_Auth_User, SystemInfo.ERP_Auth_Password);

                        if (PriEngine.EngineStatus)
                        {
                            StringBuilder status = new StringBuilder();

                            status.Append("Connected to Primavera10 Engine | ");
                            status.Append("Company: " + PriEngine.Platform.Contexto.Empresa.CodEmp + " | ");
                            status.Append("Company Name: " + PriEngine.Platform.Contexto.Empresa.IDNome + " | ");
                            status.Append("Currency: " + PriEngine.Platform.Contexto.Empresa.MoedaBase);

                            Logger.WriteEntry(status.ToString() + "\nDriver started.", EventLogEntryType.Information);
                            stop = false;
                            OnTimer();
                            timer.Start();
                            btnStart.Enabled = false;
                            btnStopDriver.Enabled = true;
                        }
                        else
                        {
                            throw new Exception("EngineStatus failed.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteEntry("Cannot acess to primavera. Check your configuration.\n" + ex.Message, EventLogEntryType.Error);
                        StopDriver();
                    }
                    break;
                default:
                    Logger.WriteEntry("The ERP type is not compatible with the Driver. ", EventLogEntryType.Error);
                    StopDriver();
                    break;
            }
        }

        private void StopDriver()
        {
            stop = true;
            timer.Stop();
            btnStopDriver.Enabled = false;
            btnStart.Enabled = true;
            Logger.WriteEntry("Driver stopped.", EventLogEntryType.Information);
        }

        private void ReloadSystemInfo()
        {
            if (!SystemInfo.ReloadSystemInfo()) StopDriver();
        }
        
        private void OnTimer()
        {
            timer.Stop();

            this.Invoke(new Action(() =>
             {
                 label2.Text = DateTime.Now.ToString();
             }));


            try {

            
            switch (SystemInfo.ERP_Type.ToUpper())
            {
                case "PRIMAVERA10":
                    Integrator.ExecuteIntegration(new ConnectorPrimavera10());
                    break;
                default:
                    Logger.WriteEntry("The ERP type is not compatible with the Driver. ", EventLogEntryType.Error);
                    StopDriver();
                    break;
            }
 } 
            catch (Exception ex) {
                Logger.WriteEntry("Error ONTimer "+ ex.Message, EventLogEntryType.Error);
            }
            if (!stop) timer.Start();
        }

        #endregion

        #region "Events"

        private void btnReloadSystemInfo_Click(object sender, EventArgs e)
        {
            ReloadSystemInfo();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            StartDriver();
        }

        private void btnStopDriver_Click(object sender, EventArgs e)
        {
            StopDriver();

            this.Invoke(new Action(() =>
            {
                label2.Text = String.Empty;
            }));
        }

        private void timer_Tick(object sender, ElapsedEventArgs e)
        {
            OnTimer();
        }

        private void btnClearConsole_Click(object sender, EventArgs e)
        {
            this.Invoke(new Action(() =>
            {
                dgvLog.Rows.Clear();
            }));
        }

        #endregion

        private void btnManualSubmission_Click(object sender, EventArgs e)
        {
            ERPManualSubmission form = new ERPManualSubmission();
            form.Show();
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (CloseCancel() == false)
            {
                e.Cancel = true;
            };
        }

        public static bool CloseCancel()
        {
            const string message = "Are you sure you want close the driver?";
            const string caption = "Close Driver";
            var result = MessageBox.Show(message, caption,
                                         MessageBoxButtons.YesNo,
                                         MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                    return true;
                else
                    return false;
        }

        private void ERPService_Load(object sender, EventArgs e)
        {

        }
    }
}
