using betrace_carfi_erp_driver.Common;
using betrace_carfi_erp_driver.Components;
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.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static betrace_carfi_erp_driver.Components.Document;



namespace betrace_carfi_erp_driver
{
    public partial class ERPManualSubmission : Form
    {
        IConnectorERP conERP;

        public ERPManualSubmission()
        {
            InitializeComponent();

            switch (SystemInfo.ERP_Type.ToUpper())
            {
                case "PRIMAVERA10":
                    this.Enabled = true;
                    conERP = new ConnectorPrimavera10();
                    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(), EventLogEntryType.Information);
                        }
                        else
                        {
                            throw new Exception("EngineStatus failed.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Logger.WriteEntry("Cannot acess to primavera. Check your configuration.\n" + ex.Message, EventLogEntryType.Error);
                    }
                    break;
                default:
                    this.Enabled = false;
                    Logger.WriteEntry("The ERP type is not compatible with the Driver. ", EventLogEntryType.Error);
                    MessageBox.Show("O tipo de ERP não é compatível com o Driver.");
                    break;
            }

            RefreshTableArticles();
            RefreshTableDocuments();
        }

        #region "Metodos"

        private void IntegrateArticles(int id)
        {
            try
            {
                Article article = Database.GetIndividualArticleToManualIntegrate(id);
                Integrator.IntegrateArticle(conERP, article);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually integrate article ID " + id + ".\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava integrar manualmente o artigo ID " + id + ".\n" + ex.Message);
            }
            RefreshTableArticles();
        }
        private void DiscardArticles(int id)
        {
            try
            {
                Database.RemoveQueueArticles(id);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually discard article ID " + id + ".\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava descartar manualmente o artigo ID " + id + ".\n" + ex.Message);
            }
            RefreshTableArticles();
        }

        private void RefreshTableArticles()
        {
            dgvArticles.DataSource = Database.GetArticlesToManualIntegrate();
            if (dgvArticles.Rows.Count > 0)
            {
                btnIntegrateArticles.Enabled = true;
                btnDiscardArticles.Enabled = true;
            }else
            {
                btnIntegrateArticles.Enabled = false;
                btnDiscardArticles.Enabled = false;
            }
        }


        private void IntegrateDocuments(int id)
        {
            try
            {
                Cab document = Database.GetIndividualDocumentToManualIntegrate(id);
                Integrator.IntegrateDocument(conERP, document);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually integrate document ID " + id + ".\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava integrar manualmente o documento ID " + id + ".\n" + ex.Message);
            }
            RefreshTableDocuments();
        }
        private void DiscardDocuments(int id)
        {
            try
            {
                Database.RemoveQueueDocuments(id, String.Empty);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually discard document ID " + id + ".\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava descartar manualmente o documento ID " + id + ".\n" + ex.Message);
            }
            RefreshTableDocuments();
        }

        private void RefreshTableDocuments()
        {
            dgvDocuments.DataSource = Database.GetDocumentsToManualIntegrate();
            if (dgvDocuments.Rows.Count > 0)
            {
                btnIntegrateDocuments.Enabled = true;
                btnDiscardDocuments.Enabled = true;
            }
            else
            {
                btnIntegrateDocuments.Enabled = false;
                btnDiscardDocuments.Enabled = false;
            }
        }
        private void RefreshTableDocumentsLines(int idCab)
        {
            dgvDocumentsLines.DataSource = Database.GetDocumentsLinesToManualIntegrate(idCab);
            
        }
        #endregion

        #region "Eventos"

        private void dgvDocuments_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int idCab = ((int) dgvDocuments.SelectedRows[0].Cells[0].Value);
            RefreshTableDocumentsLines(idCab);
        }
     


        private void btnIntegrateArticles_Click(object sender, EventArgs e)
        {
            try
            {
                IntegrateArticles((int)dgvArticles.SelectedRows[0].Cells[0].Value);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually integrate article.\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava integrar manualmente o artigo.\n" + ex.Message);
            }
        }

        private void btnDescardArticles_Click(object sender, EventArgs e)
        {
            try
            {
                DiscardArticles((int)dgvArticles.SelectedRows[0].Cells[0].Value);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually discard article.\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava descartar manualmente o artigo.\n" + ex.Message);
            }
        }

        private void btnRefreshArticles_Click(object sender, EventArgs e)
        {
            RefreshTableArticles();
        }


        private void btnIntegrateDocuments_Click(object sender, EventArgs e)
        {
            try
            {
                IntegrateDocuments((int)dgvDocuments.SelectedRows[0].Cells[0].Value);
                RefreshTableDocumentsLines((int)dgvDocuments.SelectedRows[0].Cells[0].Value);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually integrate document.\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava integrar manualmente o documento.\n" + ex.Message);
            }
        }

        private void btnDescardDocuments_Click(object sender, EventArgs e)
        {
            try
            {
                DiscardDocuments((int)dgvDocuments.SelectedRows[0].Cells[0].Value);
            }
            catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually discard document.\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava descartar manualmente o documento.\n" + ex.Message);
            }
        }

        private void btnRefreshDocuments_Click(object sender, EventArgs e)
        {
            try
            {
            RefreshTableDocuments();
                RefreshTableDocumentsLines(28);
            }
             catch (Exception ex)
            {
                Logger.WriteEntry("An error occurred while trying to manually discard document.\n" + ex.Message);
                MessageBox.Show("Ocorreu algum erro enquanto tentava descartar manualmente o documento.\n" + ex.Message);
            }
        }


        #endregion

        private void tabArticles_Click(object sender, EventArgs e)
        {

        }

       
    }
}
