using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

public partial class index : System.Web.UI.Page
{
    private string GetInternalRequestBaseUrl()
    {
        if (string.Equals(ConfigurationManager.AppSettings["IHBOX_CONTAINER_LOCAL_IIS_REQUESTS"], "true", StringComparison.OrdinalIgnoreCase))
        {
            return "http://localhost";
        }

        return "http://"
            + HttpContext.Current.Request.Url.Host
            + ":" + HttpContext.Current.Request.Url.Port;
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        WebApp.CheckSiteLanguageCookie();
        if (IhBoxSystemtConfiguration.InitialConfigurationStatus != SystemInitialConfigurationStatus.Configured)
        {
            Response.Redirect(ResolveUrl("~/landing/initConfig/initConfig.aspx"));
        }

        string loggedUsername = Convert.ToString(Session["Username"]);

        Session.Clear(); 
        Session["Username"] = WebApp.GetUserName();
        Session["Roles"] = WebApp.GetUserRoles();
        Session["MenuData"] = WebApp.GetMenu();
        Session["SecurityData"] = WebApp.GetSecurityData();

        try
        {
            string newLoggedUsername = Convert.ToString(Session["Username"]);
            if (string.IsNullOrEmpty(loggedUsername) && !string.IsNullOrEmpty(newLoggedUsername))
            {
                WebApp.AuditUserLoggedIn(newLoggedUsername);
            }
        }
        catch (Exception ex) { }
    }

    public string getJedLocaleData(string siteLang)
    {
        System.Net.WebClient client = new System.Net.WebClient();
        string text = "";
        try
        {
            string url = GetInternalRequestBaseUrl()
                + ResolveUrl("~/app/i18n/resx2json.aspx?path=dataLocalization&customPath=app/i18n&appendASPXExt=false");

            System.IO.Stream stream = client.OpenRead(url);
            System.IO.StreamReader reader = new System.IO.StreamReader(stream);
            text = reader.ReadToEnd();
        }
        catch (Exception ex)
        {
            text = "{ 'messages': { '': { 'domain': 'messages', 'lang':'en', 'plural_forms':'' } } }";
        }

        return text; 
    }

    public string getCustomModulesPaths()
    {
        JavaScriptSerializer jss = new JavaScriptSerializer(); 
        List<string> paths = new List<string>();
        
        foreach (var dir in Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory + "/app/custom-modules/"))
        {
            try
            {
                string p = ""; 
                DirectoryInfo dinfo = new DirectoryInfo(dir);
                p += dinfo.Name;

                var file = Directory.GetFiles(dinfo.FullName).FirstOrDefault(f =>
                {
                    FileInfo finfo = new FileInfo(f);
                    return finfo.Extension == ".js"; 
                }); 

                if (file != null)
                {
                    FileInfo finfo = new FileInfo(file);
                    p += "/" + finfo.Name.Replace(".js", string.Empty); 
                }

                paths.Add(p); 
            }
            catch (Exception ex)
            {
            }
        }

        StringBuilder sb = new StringBuilder(); 
        jss.Serialize(paths, sb);

        return sb.ToString(); 
    }

    public string getCustomConfigsPaths()
    {
        JavaScriptSerializer jss = new JavaScriptSerializer();
        List<string> paths = new List<string>();

        foreach (var dir in Directory.GetDirectories(AppDomain.CurrentDomain.BaseDirectory + "/app/custom-configs/"))
        {
            try
            {
                string p = "";
                DirectoryInfo dinfo = new DirectoryInfo(dir);
                p += dinfo.Name;

                var file = Directory.GetFiles(dinfo.FullName).FirstOrDefault(f =>
                {
                    FileInfo finfo = new FileInfo(f);
                    return finfo.Extension == ".js";
                });

                if (file != null)
                {
                    FileInfo finfo = new FileInfo(file);
                    p += "/" + finfo.Name.Replace(".js", string.Empty);
                }

                paths.Add(p);
            }
            catch (Exception ex)
            {
            }
        }

        StringBuilder sb = new StringBuilder();
        jss.Serialize(paths, sb);

        return sb.ToString();
    }

    private void PeformRequest(string url)
    {
        //// Create a request using a URL that can receive a post. 
        //WebRequest request = WebRequest.Create("http://" + HttpContext.Current.Request.Url.Host + 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.
        //Console.WriteLine(((HttpWebResponse)response).StatusDescription);
        //// 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.
        //Console.WriteLine(responseFromServer);
        //// Clean up the streams.
        //reader.Close();
        //dataStream.Close();
        //response.Close();     

        //using (var client = new HttpClient("http://" + HttpContext.Current.Request.Url.Host + url))
        //{
        //    var resp = client.Get();
        //    // Once you get the response from the remote service loop
        //    // through all the cookies and append them to the response
        //    // so that they are stored within the client browser.
        //    // In this collection you will get all Set-Cookie headers
        //    // sent by the service, so find the one you need and set it:
        //    foreach (var cookie in result.Headers.SetCookie)
        //    {
        //        // the name of the cookie must match the name of the authentication
        //        // cookie as you set it in your web.config.
        //        var data = cookie["SomeCookieName"];
        //        Response.AppendCookie(new HttpCookie("SomeCookieName", data));
        //    }
        //}

    }
}
