using Helpers.Log;
using log4net;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Resources;
using System.Threading;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class landing_signup_api_signup : System.Web.UI.Page
{
    private ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

    public struct userData
    {
        public string name { get; set; }
        public string lastname { get; set; }
        public string email { get; set; }
        public string country { get; set; }
        public string userid { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        TransactionLogger tranLog = new TransactionLogger(logger, MethodBase.GetCurrentMethod().Name);
        tranLog.LogDebug("Start: Sending verification email.");

        System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
        try
        {
            int uid = -1;   
           
            //System.Web.Script.Serialization.JavaScriptSerializer jss = new System.Web.Script.Serialization.JavaScriptSerializer();
            userData udata = new userData();
            //System.IO.StreamReader sr = new System.IO.StreamReader(Page.Request.InputStream);
            //string buff;
            //buff = sr.ReadToEnd();
            //udata = jss.Deserialize<userData>(buff);
            udata.userid = Request.Form["userid"];
            udata.email = Request.Form["email"]; 

            Int32.TryParse(udata.userid, out uid);
            string email = udata.email;

            if (uid == 0 && udata.userid == null)
            {
                int? systemUserId = null;
                systemUserId = DAL.getUserId(null, email);
                uid = (systemUserId != null) ? (int)systemUserId : uid;
            }

            if (uid != -1 && email != null)
            {
                Random r = new Random(DateTime.Now.Millisecond);
                string stringToEncode = email + uid + r.Next(100, 999);
                string activationKey = FormsAuthentication.HashPasswordForStoringInConfigFile(stringToEncode, "MD5");
                bool saveKey = DAL.saveKey(activationKey, uid);
                if (saveKey == true)
                {
                    bool registrationEmail = SendRegistrationEmail(email, activationKey);
                    if (registrationEmail == true)
                    {
                        //bool sendNewAccountNotification = SendNewAccountNotificationEmail("info@australtek.com", udata); 
                        bool sendNewAccountNotification = SendNewAccountNotificationEmail("jsantaana@australtek.com", udata); 
                        Response.Write(jss.Serialize(new { status = "OK" }));
                    }
                    else
                    {
                        Response.Write(jss.Serialize(new { status = "FAILED" }));
                    }
                }
                else
                {
                    Response.Write(jss.Serialize(new { status = "FAILED" }));
                }
            }
        }
        catch (Exception ex)
        {
            tranLog.LogDebug(ex, "Failed during signup API execution.");
            Response.Write(jss.Serialize(new { status = "FAILED" }));
        }
    }

    private bool SendRegistrationEmail(string email, string key)
    {
        string siteLang = "EN";
        HttpCookie lang = Request.Cookies["siteLanguage"]; 
        siteLang = (lang != null) ? lang.Value : siteLang;

        string resx = AppDomain.CurrentDomain.BaseDirectory + "\\landing\\api\\App_LocalResources\\resources" + ((siteLang == "EN") ? "" : "." + siteLang) + ".resx"; 
        System.Resources.ResXResourceReader rsxr = new System.Resources.ResXResourceReader(resx);
        Dictionary<string, string> resourceMap = new Dictionary<string, string>();
        foreach (DictionaryEntry d in rsxr)
            resourceMap.Add(d.Key.ToString(), d.Value.ToString());

        rsxr.Close();

        string systemEmail = ConfigurationManager.AppSettings["systemEmail"]; 
        string systemEmailPassword = ConfigurationManager.AppSettings["systemEmailPassword"]; 

        string templateURL = string.Format("{0}?key={1}", "http://" + Request.Url.Host + Request.ApplicationPath + "/landing/email-templates/simple-sign-up.aspx", key);
        string messageBody = Mail.GetEmailTemplate(templateURL, Request.Url.ToString(), Request.Cookies["siteLanguage"]);

        bool result = false;
        result = Mail.SendEmail(email, resourceMap["registration_email_subject"], messageBody); 

        return result; 
    }
    private bool SendNewAccountNotificationEmail(string email, userData udata)
    {
        bool result = false; 
        try
        {
            string systemEmail = ConfigurationManager.AppSettings["systemEmail"];
            string systemEmailPassword = ConfigurationManager.AppSettings["systemEmailPassword"];

            MailMessage mailmessage = new MailMessage(new MailAddress(systemEmail)
                                               , new MailAddress(email));
            mailmessage.Subject = "IHBox: New account created";
            mailmessage.IsBodyHtml = true;
            mailmessage.Body = "<b>NEW ACCOUNT CREATED ON IHBOX: <b><br/><b>E-mail: " + udata.email + "<b><br/>"; 
            //mailmessage.Body = "<B>New account created: </B><br />User info:<br/ > " + "<br />Account Number: " + rd.id + "<br />Name: " + rd.name + "<br />" +
            //    "Last Name: " + rd.lastName + "<br />Email: " + rd.email + "<br/>Company: " + rd.company + "<br/>Address: " + rd.address +
            //    "<br />Phone number: " + rd.phoneNumber
            //    ;

            System.Net.NetworkCredential networkCredentials = new
                System.Net.NetworkCredential(systemEmail, systemEmailPassword);

            SmtpClient smtpClient = new SmtpClient();
            smtpClient.EnableSsl = true;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = networkCredentials;
            smtpClient.Host = "smtp.gmail.com";
            smtpClient.Port = 587;

            smtpClient.Send(mailmessage);
            result = true; 
        }
        catch (Exception ex)
        {
            logger.Error("SendNewAccountNotificationEmail. Failed. ", ex);
            result = false; 
        }
        return result;
    }
}