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 System.Net;
using System.IO;
using LLNet.Utils;


namespace LLNet.Tienda.MainForms.Forms.GiftCard
{
    public partial class FrmNumGiftCard : Form
    { 
        private string varUrlPts, varCodemprPts, varCodsucPts, vartarj;
            public string saldo, tarj;
        

        public FrmNumGiftCard()
        {
            InitializeComponent();
            LlenarParametros();
        }

        private void btnAsigCli_Click(object sender, EventArgs e)
        {
            tarj = txtTarjet.Text;
            //if (Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS.Count == 0 || Program.FrmMainPos.DsPedido.WMS_DOCUMENTOS[0]["TOTAL"] == DBNull.Value)
            //{
            //    GUI.CApp.ShowMessage("No puedes pagar con GiftCatd si no tienes productos", "GiftCard", true);
            //    this.Close();
            //    this.Dispose();
            //}
            //else
            //{
                //Longitud gift card
                int longGC = int.Parse(Helpers.Nvl(CApp.GetParam("LGC"), "").ToString());

                //llamada x tarjeta
                //if (this.txtTarjet.Text.Length != longGC)
                //{
                //    this.txtTarjet.Focus();
                //    CApp.ShowMessage("¡El número de tarjeta debe ser de " + longGC + " caracteres!", "GiftCard", true);
                //}
                //else
                //{
                   string tj = txtTarjet.Text.Trim();
                   if (tj != "")
                   {
                       saldo = Consultar_SALDO(tarj);
                       GUI.CApp.ShowMessage(" Saldo Disponible: " + saldo , "GiftCard", true);
                   }
                    this.Close();
                    this.Dispose();
                //}
            //}
        }

        #region MISPUNTOS

        private string Consultar_SALDO(string ptarjeta)
        {

            string info = RequestPOST(varUrlPts + "consultar_tarjeta_regalo.inc.php", "url_respuesta=" + varUrlPts + "prueba_respuesta.php&tipo_respuesta=1&cod_empresa=" + varCodemprPts + "&numero_tarjeta=" + ptarjeta);
            string[] datos = info.Split(' ');
            if (datos.Length > 4)
            {
                if (datos[3] == "10")
                {
                    string saldo = datos[2].ToString();

                    if (saldo.LastIndexOf('.') > 0)
                    {
                        saldo = saldo.Substring(0, saldo.LastIndexOf('.'));
                    }
                    return saldo;
                }
                else
                {//se puede almacenar el error --falta
                    return "0";
                }
            }
            else
            {
                return "0";
            }
        }

       
        /// <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();
        }

        //almacena el error en el WS
        private void BitacoraErrorWS(string pError, string pWServ)
        {
            if (pWServ.Length > 300)
                pWServ = pWServ.Substring(0, 300);
            Utils.QueryParams qp = new LLNet.Utils.QueryParams();
            qp.AddReplaceParam("pError", pError);
            qp.AddReplaceParam("pWServ", pWServ);
            // Llama el procedimiento que almacena el error del WS en la BD
            GUI.CApp.bll.ExecuteSql("WMS_P_BITAC_E_AFIL", qp, "PDV");
        }

        #endregion

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtTarjet_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnAsigCli_Click (null,null);
            }
        }     
      
    }
}