using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Text;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

/// <summary>
/// Summary description for AEPS
/// </summary>
public class AEPS
{
  // static string baseurl = "https://staging.spicemudra.com/spayg/finaeps/ws/";
   static string baseurl = "https://api.spicemoney.com/spayg/finaeps/ws/";
   static string MerchantId = "VENUS001";
   string path = "";
   string url = "";
   string city, pincode, state;
   AirEpointSupport _objTransaction = new AirEpointSupport();
   string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    public string way_in(string AgentID)
    {
        path = "wayin/v1";
        url = baseurl + path;
        string uniqueId=_objTransaction.Generate_TID();
        DataTable dt = GetAgentDetails(AgentID);
        if (dt.Rows.Count > 0)
        {
            city = Convert.ToString(dt.Rows[0]["city"]);
            pincode = Convert.ToString(dt.Rows[0]["pincode"]);
            state = Convert.ToString(dt.Rows[0]["state"]);
        }
        else
        {
            city = "Deoghar";
            pincode = "700050";
            state = "Kolkata";
        }
        string json = new JavaScriptSerializer().Serialize(new
        {
            uniqueId = uniqueId,
            requestIp = IPAddress,
            sessionId = uniqueId,
            token = uniqueId,
            merchantId = MerchantId,
            remarks = "",
            agentId = AgentID,
            agentCity = city,
            agentPin = pincode,
            agentState = state,
            requestType = "AEPS",
            requestMode = "WEB",
            requestFor = "Native",
            requestMedium = "WEB",
            udf1 = "",
            udf2 = "",
            udf3 = "",
            udf4="",
            udf5=""
        });

        InsrtLog(AgentID, uniqueId, uniqueId, uniqueId, url,json);
        string Result = PostRequest(url, json);
        Result = Result.Replace("NULL", "");
        Result = Result.Replace("}", ",}");
        JObject joResponse = JObject.Parse(Result);
        JValue ResponseStatus = (JValue)joResponse["responseStatus"];
        JValue Code = (JValue)joResponse["responseCode"];
        JValue Description = (JValue)joResponse["responseDesc"];
        JObject payload = (JObject)joResponse["payload"];
        JValue UniqueID = (JValue)payload["uniqueId"];
        JValue UniqueRefId = (JValue)payload["uniqueRefNo"];
        JValue WLUrl = (JValue)payload["wlUrl"];
        updateLog(uniqueId, Result, Convert.ToString(UniqueRefId));
        string ReturnValue = "";
        if (Convert.ToString(ResponseStatus).ToUpper() == "SU")
        {
            ReturnValue = ResponseStatus.ToString() + '-' + Convert.ToString(WLUrl);
        }
        else
        {
            ReturnValue = ResponseStatus.ToString() + '-' + Convert.ToString(Description);
        }
        return ReturnValue;
    }

    public void updateLog(string UniqueId, string Result,string UniqueRefID)
    {
        SqlParameter[] TxnResponce = new SqlParameter[]
                    {
                         
                        new SqlParameter("@UniqueId",UniqueId),
                        new SqlParameter("@Response",Result),
                        new SqlParameter("@UniqueRefId",UniqueRefID)
                    };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UpdateLog_AEPS", TxnResponce);
    }


    public void InsrtLog(string AgentId, string UniqueId, string SessionId, string Token, string url, string RequestJSON)
    {
        SqlParameter[] TxnResponce = new SqlParameter[]
                    {
                         new SqlParameter("@AgentID",AgentId),
                        new SqlParameter("@UniqueId",UniqueId),
                        new SqlParameter("@SessionId",SessionId),
                        new SqlParameter("@Token",Token),
                        new SqlParameter("@URL",url),
                        new SqlParameter("@RequestJSON",RequestJSON)
                    };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "InserLog_AEPS", TxnResponce);
    }
    private string PostRequest(string url, string json)
    {
        string result = "";
        try
        {
            HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(url);
            Encoding encoding = new UTF8Encoding();
            string postData = json;
            byte[] data = encoding.GetBytes(postData);
            httpWReq.ProtocolVersion = HttpVersion.Version11;
            httpWReq.Method = "POST";
            httpWReq.ContentType = "application/json"; 

            string _auth = string.Format("{0}:{1}", "vE#u$@ePs3818","VeNus@Ep(3818)");
            string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
            string _cred = string.Format("{0} {1}", "Basic", _enc);
            //httpWReq.Headers.Add(HttpRequestHeader.Authorization,  
            // "Bearer " + accessToken);  

            httpWReq.Headers[HttpRequestHeader.Authorization] = _cred;
            httpWReq.ContentLength = data.Length;


            Stream stream = httpWReq.GetRequestStream();
            stream.Write(data, 0, data.Length);
            stream.Close();

            HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
            string s = response.ToString();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            String jsonresponse = "";
            String temp = null;
            while ((temp = reader.ReadLine()) != null)
            {
                jsonresponse += temp;
            }
            return jsonresponse;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }
    public DataTable GetAgentDetails(string LoginID)
    {
        string sql = "select isnull(OFFICECITY,'Deoghar') city,isnull(OFFICEPIN,'700050') pincode,isnull(OFFICESTATE,'Kolkata') state from user_information where COURENTLEVEL=(select LOGINID from login_detail where UserName='" + LoginID + "')";
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, sql);
        return ds.Tables[0];
    }
    
}