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 NewAccountKS : System.Web.UI.Page
    {
        protected string lmessage = "There is no account associated with the given Keystone ID. Do you want to create a new account, or to link this Keystone ID with an existing CasJobs account?";
        protected string newFullName;
        protected string newUserId;
        protected string newEmail;
        protected string keystoneId;

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string token = Request.Cookies["Keystone"]["token"];
                var userAccess = Keystone.Authenticate(token);
                keystoneId = userAccess.User.Id;
                newUserId = userAccess.User.Name;
                newFullName = newUserId;
                newEmail = newUserId + "@skyserver.sdss3.org";
            }
            catch (Exception ex)
            {
                lmessage = "ERROR! Could not obtain user info from Keystone provider. " + ex;
            }
        }

        protected void ButtonOK_Click(object sender, EventArgs e)
        {
            try
            {

                    CasUsers cu = new CasUsers();
                    long? wsid;
                    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];
                                user.KeystoneID = keystoneId;
                                cu.UpdateAccount(wsid.Value, user);
                            }

                        }
                    }
                    else // create a new account
                    {
                        try
                        {
                            wsid = Keystone.GetWebServicesId(keystoneId);
                            if (wsid == null) throw new Exception("CasJobs user with the given Keystone ID does not exist");
                        }
                        catch (Exception ex)
                        {
                            long serviceID = long.Parse(ConfigurationSettings.AppSettings["ServiceID"]);
                            string password = System.Web.Security.Membership.GeneratePassword(10, 0);
                            wsid = cu.CreateAccount(serviceID, newUserId, newFullName, newEmail, password, null, 0, 1);
                            User user = cu.FindUser(edu.jhu.Cas.Util.ID.SERVICE_ID, "WEBSERVICESID=" + wsid)[0];
                            user.KeystoneID = keystoneId;
                            cu.UpdateAccount(wsid.Value, user);
                        }
                    }

                    Response.Redirect("SubmitJob.aspx");

            }
            catch (Exception ex)
            {
                lmessage = "ERROR! " + ex.Message;
            }
        }

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