using Helpers.Log;
using log4net;
using System;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Reflection;
using System.Web;

/// <summary>
/// Summary description for Mail
/// </summary>
public static class Mail
{
    private static ILog logger = Logger.GetLogger(MethodBase.GetCurrentMethod().DeclaringType.Name);

    //static Mail()
    //{
    //    LogHelper.Log.LoggerName = "";
    //    LogHelper.Log.DisplayMethods = true;
    //}

    public static bool SendEmail(string to, string subject, string body)
    {
        TransactionLogger tranLog = new TransactionLogger(logger, MethodBase.GetCurrentMethod().Name);
        bool result = false; 
        string systemEmail = ConfigurationManager.AppSettings["systemEmail"];
        string systemEmailPassword = ConfigurationManager.AppSettings["systemEmailPassword"]; 

        try
        {
            MailMessage mailmessage =
                new MailMessage(new MailAddress(systemEmail), new MailAddress(to));
            mailmessage.Subject = subject;
            mailmessage.IsBodyHtml = true;
            mailmessage.Body = body; 

            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;

            tranLog.Log(string.Format("Sending email to Email [{0}] .", to));

            try
            {
                smtpClient.Send(mailmessage);
                result = true;
            }
            catch (Exception ex)
            {
                tranLog.Log("Failed when sending Email. Exception: " + ex.Message);
                //mail couldn´t be sended so we let info@australtek.com know something is failing with google´s server
                //sending mail to info
                mailmessage = new MailMessage(new MailAddress("australtek@outlook.com")
                                               , new MailAddress("info@australtek.com"));
                mailmessage.Subject = "IHBox: Error! GMAIL Servers.";
                mailmessage.IsBodyHtml = true;
                mailmessage.Body = "Mail through Google´s servers couldnt be sent.";
                networkCredentials = new
                System.Net.NetworkCredential("australtek@outlook.com", "Future2040");
                smtpClient = new SmtpClient();
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = networkCredentials;
                smtpClient.Host = "smtp.live.com";
                smtpClient.Port = 587;
                smtpClient.Send(mailmessage);

                result = false;
            }
        }
        catch (Exception ex)
        {
            result = false; 
        }
        return result; 
    }

    public static string GetEmailTemplate(string url, string requestUrl, HttpCookie lang)
    {
        TransactionLogger tranLog = new TransactionLogger(logger, MethodBase.GetCurrentMethod().Name);
        string result = String.Empty;
        try
        {
            //HTML simple version
            tranLog.Log("Getting email template from: " + url);
            WebRequest req = WebRequest.Create(url);
            HttpWebRequest httpRequest = req as HttpWebRequest;
            if (httpRequest != null && httpRequest.CookieContainer == null)
            {
                httpRequest.CookieContainer = new CookieContainer();
                httpRequest.CookieContainer.Add(new Uri(requestUrl), new Cookie(lang.Name, lang.Value, lang.Path));
            }
            // Get the stream from the returned web response
            StreamReader stream = new StreamReader(req.GetResponse().GetResponseStream());
            // Get the stream from the returned web response
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string strLine;
            // Read the stream a line at a time and place each one
            // into the stringbuilder
            while ((strLine = stream.ReadLine()) != null)
            {
                // Ignore blank lines
                if (strLine.Length > 0)
                    sb.Append(strLine);
            }
            // Finished with the stream so close it now
            stream.Close();
            result = sb.ToString();  //replace 'string results' with 'return' if u are calling it.
        }
        catch (Exception ex)
        {
            tranLog.Log(ex, "GetEmailTemplate. Failed.");
        }
        return result;
    }
}