using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DotNetOpenAuth.OpenId.RelyingParty;
using DotNetOpenAuth.OpenId.Extensions.AttributeExchange;
using edu.jhu.Cas.Users;
using System.Configuration;
using edu.jhu.Cas.Util;

namespace edu.jhu.Cas.Web
{
    public partial class NewAccount : System.Web.UI.Page
    {
        protected string lmessage = "There is no account associated with the given OpenID. Do you want to create a new account, or to link this OpenID with an existing CasJobs account?" +
            "<br/>If you already have an acoount created with another OpenID, please go back to the login page and log in using that OpenID. <br/>You will be able to add additional OpenID's from your profile page.";
        protected string newFullName;
        protected string newUserId;

        protected void Page_Load(object sender, EventArgs e)
        {
            var response = (IAuthenticationResponse)Session["OID_RESPONSE"];
            if (response != null && response.Status == AuthenticationStatus.Authenticated)
            {
                try
                {
                    FetchResponse fetch = response.GetExtension<FetchResponse>();
                    string email = String.Empty;
                    string name = String.Empty;
                    if (fetch != null)
                    {
                        email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                        string fullname = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);

                        if (fullname == null || String.Empty.Equals(fullname))
                        {
                            string firstname = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                            string lastname = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                            name = firstname + " " + lastname;
                        }
                        else
                        {
                            name = fullname;
                        }
                        newFullName = name;
                        newUserId = email;
                    }
                    else throw new Exception("Could not read OpenID extensions.");
                }
                catch (Exception ex)
                {
                    lmessage = "ERROR! Could not obtain user info from OpenID provider. " + ex;
                }
            }
            else
            {
                Response.Redirect("login.aspx?lmessage=" + HttpUtility.UrlEncode("You are not logged in. Please try again."));
            }
        }

        protected void ButtonOK_Click(object sender, EventArgs e)
        {
            var response = (IAuthenticationResponse)Session["OID_RESPONSE"];
            try
            {
                if (response != null && response.Status == AuthenticationStatus.Authenticated)
                {

                    CasUsers cu = new CasUsers();
                    long wsid = 0;
                    string userid = "";

                    if (Request["radio"] == "RadioLink")
                    {
                        string casJobsUID = Request.Params["userid"];
                        string casJobsPassword = Request.Params["password"];
                        if (casJobsUID != null && casJobsUID.Length > 0)
                        {
                            long id = 0;

                            id = cu.GetWebServiceId(casJobsUID, casJobsPassword);
                            if (id <= 0)
                            {
                                throw new Exception("Invalid User ID / Password combination, please try again.");
                            }
                            else
                            {
                                userid = casJobsUID;
                                wsid = id;
                                User user = cu.FindUser(edu.jhu.Cas.Util.ID.SERVICE_ID, "WEBSERVICESID=" + wsid)[0];
                                List<string> l = user.OpenID.ToList();
                                l.Add(response.ClaimedIdentifier.ToString());
                                user.OpenID = l.ToArray();
                                cu.UpdateAccount(wsid, user);
                            }

                        }
                    }
                    else // create a new account
                    {
                        FetchResponse fetch = response.GetExtension<FetchResponse>();
                        string email = String.Empty;
                        string name = String.Empty;
                        if (fetch != null)
                        {
                            email = fetch.GetAttributeValue(WellKnownAttributes.Contact.Email);
                            string fullname = fetch.GetAttributeValue(WellKnownAttributes.Name.FullName);

                            if (fullname == null || String.Empty.Equals(fullname))
                            {
                                string firstname = fetch.GetAttributeValue(WellKnownAttributes.Name.First);
                                string lastname = fetch.GetAttributeValue(WellKnownAttributes.Name.Last);
                                name = firstname + " " + lastname;
                            }
                            else
                            {
                                name = fullname;
                            }
                        }
                        else
                        {
                            throw new Exception("Could not create a new account. Could not read OpenID extensions.");
                        }

                        try
                        {
                            wsid = GetWebServiceId(response.ClaimedIdentifier.ToString());
                        }
                        catch (Exception ex)
                        {
                            long serviceID = long.Parse(ConfigurationSettings.AppSettings["ServiceID"]);
                            string password = System.Web.Security.Membership.GeneratePassword(10, 0);
                            wsid = cu.CreateAccount(serviceID, email, name, email, password, null, 0, 1);
                            User user = cu.FindUser(edu.jhu.Cas.Util.ID.SERVICE_ID, "WEBSERVICESID=" + wsid)[0];
                            user.OpenID = new string[] { response.ClaimedIdentifier.ToString() };
                            cu.UpdateAccount(wsid, user);
                        }

                        userid = GetUserId(wsid);
                    }

                    Session["USER"] = wsid;
                    Session["USERID"] = userid;
                    Global.users.Add(userid);
                    try
                    {
                        cu.HasPrivilege(wsid, PRIVS.ADMIN);
                        Session["ADMIN"] = true.ToString();
                    }
                    catch
                    {
                        Session["ADMIN"] = false.ToString();
                    }
                    Session.Remove("OID_RESPONSE");
                    Response.Redirect("SubmitJob.aspx");

                }
                else Response.Redirect("login.aspx?lmessage=" + HttpUtility.UrlEncode("You are not logged in. Please try again."));
            }
            catch (Exception ex)
            {
                lmessage = "ERROR! " + ex.Message;
            }
        }

        protected void ButtonCancel_Click(object sender, EventArgs e)
        {
            Session.Remove("OID_RESPONSE");
            Response.Redirect("login.aspx");
        }

        private string GetUserId(long wsid)
        {
            return SqlFactory.scalar("select userid from users where webservicesid = '" + wsid + "'").ToString();
        }

        private long GetWebServiceId(string openId)
        {
            return long.Parse(
                 SqlFactory.scalar("select wsid from openid where openid = '" + openId + "'").ToString());
        }
    }
}