using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using LLNet.GUI;
using LLNet.Utils;
using System.Net;
using System.IO;

namespace LLNet.Tienda.MainForms.Forms.GiftCard
{
    public partial class FrmGiftCard : Form
    {
        bool Nuevo = false;
        public string GiftCard = "";
        private string varUrlPts, varCodemprPts, varCodsucPts;
        int NumLinea = 0;

        public FrmGiftCard(bool nuevo)
        {
            InitializeComponent();

            this.Nuevo = nuevo;
            if(this.Nuevo)
                this.btnAceptar.Text = "[F12]                                                                Activar";
            else
                this.btnAceptar.Text = "[F12]                                                                Recargar";

            this.txtTarjeta.Focus();
        }

        #region AgregarProductoGC
        /// <summary>
        /// Agrega al dataset del pedido, la gift card
        /// </summary>
        private void AgregarProductoGC()
        {
            decimal vSku = Convert.ToDecimal(GUI.CApp.GetParam("SPIC"));
            Utils.QueryParams qp = new QueryParams();
            qp.AddReplaceParam("SKU", vSku.ToString());

            if (GUI.CApp.bll.GetSingleValue("FindSku", qp, "PDV").ToString() != "0")
            {
                if (Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS.Count == 0)
                {
                    if (Program.FrmMainPos.pos.ctlAddSkus1.CreateOrder(null) == -1)
                        return;

                    Program.FrmMainPos.RefreshData();
                }

                qp.Clear();
                qp.AddReplaceParam("SKU", vSku.ToString());

                //decimal vPctImp = Convert.ToDecimal(GUI.CApp.bll.GetSingleValue("GetTaxes", qp, "PDV"));
                decimal vPrecio = decimal.Parse(this.txtMonto.Text);
                decimal vPrecioUnitario = vPrecio;// / (1 + (vPctImp / 100))
                decimal vImpuesto = vPrecio - vPrecioUnitario;

                Program.FrmMainPos.pos.ctlAddSkus1.InsertOrderLine(null, 1, GUI.CApp.usuario, vPrecioUnitario, null,
                     null, null, vSku, null, null, null);
               
                GiftCard = this.txtTarjeta.Text;
            }

            Program.FrmMainPos.RefreshData();
        }
        #endregion

        #region NumLineaGiftCard

        public void AgregarNumLinea(int pTipo) 
        {
            if (Program.FrmMainPos.DsPedido.WMS_SKUS_X_DOCUMENTO.Count > 0)
            {
                NumLinea = Program.FrmMainPos.DsPedido.WMS_SKUS_X_DOCUMENTO.Count -1;
                Utils.QueryParams qp = new QueryParams();
                qp.AddReplaceParam("TARJETA", this.txtTarjeta.Text);
                qp.AddReplaceParam("DOCUMENTO", Program.FrmMainPos.DsPedido.WMS_SKUS_X_DOCUMENTO[0].DOCUMENTO.ToString());
                qp.AddReplaceParam("LINEA", Program.FrmMainPos.DsPedido.WMS_SKUS_X_DOCUMENTO[NumLinea].LINEA.ToString());
                qp.AddReplaceParam("TIPO", pTipo.ToString());
                GUI.CApp.bll.ExecuteSql("IncluirNumLineaxGiftCard", qp, "PDV");
            }
        }


        #endregion

        #region Activar
        /// <summary>
        /// Activa la gift card
        /// </summary>
        private void Activar()
        {
            if (Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS.Count == 0)
            {
                if (Program.FrmMainPos.pos.ctlAddSkus1.CreateOrder(null) == -1)
                    return;

                Program.FrmMainPos.RefreshData();
            }
                      
            Utils.QueryParams qp = new QueryParams();
            qp.AddReplaceParam("TARJETA", this.txtTarjeta.Text);
            qp.AddReplaceParam("USUARIO", GUI.CApp.usuario);
            qp.AddReplaceParam("DOCPEDIDO", Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS[0].DOCUMENTO.ToString());
            qp.AddReplaceParam("MONTO", this.txtMonto.Text);

            GUI.CApp.bll.ExecuteSql("WMS_P_ALMGIFTCARD", qp, "PDV");

            AgregarProductoGC();
            AgregarNumLinea(1);
            this.Dispose();
        }
        #endregion

        #region Recargar
        /// <summary>
        /// Recarga la gift card
        /// </summary>
        private void Recargar()
        {
            if (Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS.Count == 0)
            {
                if (Program.FrmMainPos.pos.ctlAddSkus1.CreateOrder(null) == -1)
                    return;

                Program.FrmMainPos.RefreshData();
            }

            Utils.QueryParams qp = new QueryParams();
            qp.AddReplaceParam("TARJETA", this.txtTarjeta.Text);
            qp.AddReplaceParam("USUARIO", GUI.CApp.usuario);
            qp.AddReplaceParam("DOCUMENTO", Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS[0].DOCUMENTO.ToString());
            qp.AddReplaceParam("MONTO", this.txtMonto.Text);

            GUI.CApp.bll.ExecuteSql("WMS_P_RECGIFTCARD", qp, "PDV");

            AgregarProductoGC();
            AgregarNumLinea(2);
            this.Dispose();
        }
        #endregion

        #region sbtnSalir_Click
        private void sbtnSalir_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
        #endregion

        #region FrmGiftCard_KeyDown
        private void FrmGiftCard_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                switch (e.KeyCode)
                {
                    case Keys.Escape:
                        this.Dispose();
                        break;
                    case Keys.F12:
                        btnAceptar_Click(null, null);
                        break;
                }
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Gift Card", true);
            }
        }
        #endregion

        #region btnAceptar_Click
        private void btnAceptar_Click(object sender, EventArgs e)
        {
            try
            {
                //Longitud gift card
                int longGC = int.Parse(Helpers.Nvl(CApp.GetParam("LGC"), "").ToString());

                if (this.txtTarjeta.Text == String.Empty)
                {
                    CApp.ShowMessage("Ingrese la tarjeta", "Gift Card", true);
                    this.txtTarjeta.Focus();
                }
                else if (this.txtTarjeta.Text.Length != longGC)
                {
                    CApp.ShowMessage("El número de la gift card deber ser de " + longGC + " caracteres", "Gift Card", true);
                    this.txtTarjeta.Focus();
                }
                else if (this.txtMonto.Text == String.Empty)
                    if (this.Nuevo)
                    {
                        CApp.ShowMessage("Ingrese el monto de la tarjeta", "Gift Card", true);
                        this.txtMonto.Focus();
                    }
                    else
                    {
                        CApp.ShowMessage("Ingrese el monto a recargar", "Gift Card", true);
                        this.txtMonto.Focus();
                    }
                else if (Convert.ToDecimal(this.txtMonto.Text) <= 0)
                {
                    CApp.ShowMessage("El monto debe ser mayor a cero", "Gift Card", true);
                    this.txtMonto.Focus();
                }
                else
                {
                    if (this.Nuevo)
                    {
                        Utils.QueryParams qp = new QueryParams();
                        qp.AddReplaceParam("TARJETA", this.txtTarjeta.Text);
                        object resul = GUI.CApp.bll.GetSingleValue("GiftCExiste", qp, "PDV");
                        if(resul != null)
                            if(resul.ToString() == "0")
                                Activar();
                            else
                                CApp.ShowMessage("La gift card ya está activada", "Gift Card", true);
                        else
                            CApp.ShowMessage("No se puede validar la gift card", "Gift Card", true);
                    }
                    else
                        Recargar();
                }
            }
            catch (FormatException)
            {
                CApp.ShowMessage("Digite un monto válido", "Gift Card", true);
                this.txtMonto.Focus();
            }
            catch (Exception ex)
            {
                CApp.ShowMessage(ex.Message, "Gift Card", true);
            }
        }
        #endregion

        #region ProveedorPTS-GiftCard

        /// <summary>Ejecuta por medio de post un llamado al Web Service utilizando HTTP POST</summary>
        /// <param name="URL"></param>
        /// <param name="PostData"></param>
        /// <returns></returns>
        private string RequestPOST(string URL, string PostData)
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create(URL);
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            //string postData = "";
            byte[] byteArray = Encoding.UTF8.GetBytes(PostData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            // MessageBox.Show(((HttpWebResponse)response).StatusDescription, "DESCRIPCION");
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.            
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
            return responseFromServer;
        }

        /// <summary>Obtiene los parámetros necesarios de cada tienda </summary>
        private void LlenarParametros()
        {
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            //CONSULTA LOS PARÁMETROS DE LA BD
            DataSet dsB = GUI.CApp.bll.getDataSet("PDV", "C_PPTS", qp);

            object[] datos = new object[3];
            datos = dsB.Tables[0].Rows[0].ItemArray;

            varUrlPts = datos[0].ToString();
            varCodemprPts = datos[1].ToString();
            varCodsucPts = datos[2].ToString();
        }
                
        #endregion
    }
}