using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.Configuration;
namespace CallApiPalexpo
{
    class Program
    {
        static void Main(string[] args)
        {

            ContextDataBase dcPrj = new ContextDataBase(CryptorEngine.CryptConnexionString(ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString));
            string sDate = dcPrj.ZINS.Where(cc => cc.ZINS_COD == "PALEXPO_WS").First().ZINS_PAR;
            WebRequest request2 =
             WebRequest.Create(@"https://api.palexpo.ch:8443/token");
            string encodedUserCredentials =
    Convert.ToBase64String(
       System.Text.ASCIIEncoding.ASCII.GetBytes(ConfigurationManager.AppSettings["CLES"]));
            request2.ContentType = @"application/json; charset=utf-8";
            request2.Method = "POST";
            request2.ContentType = "application/x-www-form-urlencoded";
            var userData = "grant_type=password&username=novative&password=Novative123";
            request2.Headers.Add("Authorization", "Basic " + encodedUserCredentials);
            // request2.Headers.Add("Authorization", "Basic " + encodedUserCredentials);

            StreamWriter requestWriter = new StreamWriter(request2.GetRequestStream());
            requestWriter.Write(userData);
            requestWriter.Close();
            string sKey = "";
            // var response = request2.GetResponse() as HttpWebResponse;

            HttpWebResponse response2 = (HttpWebResponse)request2.GetResponse();
            string jsonResponse2 = string.Empty;
            using (StreamReader sr = new StreamReader(response2.GetResponseStream()))
            {
                jsonResponse2 = sr.ReadToEnd();
                var jss = new JavaScriptSerializer();
                Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(jsonResponse2);
                sKey=sData["access_token"].ToString();
                //  Console.WriteLine(jsonResponse2);
                //   Console.ReadLine();



            }


            WebRequest request = WebRequest.Create(@"https://api.palexpo.ch:8443/services/project/1.0.0/search?after_updatedate="+sDate);

            // WebRequest request = WebRequest.Create(@"https://api.palexpo.ch/store/api/services/project/1.0.0/search?after_updatedate=01.01.2017");

            request.Method = "GET";
            //  request.Headers.Add("api_key", "e9cf5706-2885-3a0e-aac1-6e37be774ad7");
            //  request.Headers["Authorization"] = "Basic" + Convert.ToBase64String(Encoding.Default.GetBytes("novative:Novative123"));
            //  client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
            request.Headers["Authorization"] = "Bearer "+sKey;
            request.ContentLength = 0;
            request.ContentType = @"application/json; charset=utf-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string jsonResponse = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
               
                jsonResponse = sr.ReadToEnd();

                var jss = new JavaScriptSerializer();
               // Dictionary<string, string> sData = jss.Deserialize<<string, string>>(jsonResponse);
               // var jss2 = new JavaScriptSerializer();
               // string sLstProduct = jsonResponse.Substring(0, jsonResponse.Length - 3).Replace("{\"ProjectList\":{", "");
                 Dictionary<string, object> sData2 = jss.Deserialize<Dictionary<string, object>>(jsonResponse);
                 var arrayprj = sData2["ProjectList"] as Dictionary<string, object>;
                 var lstprj= arrayprj["Project"] as System.Collections.ArrayList;
                 int iPas = int.Parse(ConfigurationManager.AppSettings["PAS"]);
                string sSstaTst=ConfigurationManager.AppSettings["STA_PRJ"];
                try
                {
                    for (int idx = 0; idx < lstprj.Count; idx++)
                    {
                        var project = lstprj[idx] as Dictionary<string, object>;
                        string sCode = project["EventId"].ToString();
                        string sSstaLib = project["EventDescription"].ToString();
                        string sSStaVis = project["TimesheetFlag"].ToString();
                        int isStaVis = (sSStaVis == "Y") ? 0 : 1;
                        if (!string.IsNullOrEmpty(sSstaLib))
                        {
                            if (dcPrj.SSTAs.Where(cc => cc.SSTA_PAS == iPas && cc.SSTA_TST == sSstaTst
                                && cc.SSTA_NUM == sCode).ToList().Count == 0)
                            {
                                dcPrj.SSTAs.InsertOnSubmit(new SSTA()
                                {

                                    SSTA_NUM = sCode,
                                    SSTA_TST = sSstaTst,
                                    SSTA_LIB = sSstaLib,
                                    SSTA_PAS = iPas,
                                    SSTA_VIS = isStaVis
                                });
                            }
                            else
                            {
                                dcPrj.SSTAs.Where(cc => cc.SSTA_PAS == iPas && cc.SSTA_TST == sSstaTst
                                && cc.SSTA_NUM == sCode).First().SSTA_VIS = isStaVis;
                            }
                        }
                    }
                    dcPrj.SubmitChanges();
                    dcPrj.ZINS.Where(cc => cc.ZINS_COD == "PALEXPO_WS").First().ZINS_PAR = string.Format("{0:yyyy-MM-dd}", DateTime.Now.Date.AddDays(-1));
                    dcPrj.SubmitChanges();
                }
                catch (Exception ex)
                {
                    ContextDataBase dcPrj2 = new ContextDataBase(CryptorEngine.CryptConnexionString(ConfigurationManager.ConnectionStrings["OraConnection"].ConnectionString));
                    DateTime dtNow = DateTime.Now;
                    int iDat = int.Parse(String.Format("{0:yyyyMMdd}", dtNow));
                    int iHre = int.Parse(String.Format("{0:HHmmss}", dtNow));
                    try
                    {

                        dcPrj2.Zerrs.InsertOnSubmit(new Zerr()
                        {
                            ZerrPrg = "PALEXPO_WS",
                            ZerrMsg = (ex.Message.Length < 254) ? ex.Message : ex.Message.Substring(0, 254),
                            ZerrKey = (ex.InnerException.Message.Length < 254) ? ex.InnerException.Message : ex.InnerException.Message.Substring(0, 254),
                            ZerrDat = iDat,
                            ZerrHre = iHre,
                            ZerrIdu = "NOVAP",
                            ZerrPas = 0,
                            ZerrMat = 0,
                            ZerrNum = "",

                        });
                        dcPrj2.SubmitChanges();
                        //return "succées";
                    }
                    catch (Exception ex2)
                    {
                        string sMsg = ex2.Message;
                        // return sMsg;
                    }
                }

              //  var jarray = JsonConvert.DeserializeObject<Product>(sLstProduct);
                //Console.WriteLine(jsonResponse);
                //Console.ReadLine();

            }

            }
             
        
     }
   
    public class Project
    {


        public string EventId;
        public string StartDate;
        public int OrganisationCode;
        public string EventDescription;
        public string TimesheetFlag;

        public string UpdateStamp;

    }
   
}
