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

namespace edu.jhu.Cas.Web
{
    public partial class ChangeDetails : System.Web.UI.Page
    {
        protected long wsid;
        protected string lmessage;
        protected string pmessage;
        protected edu.jhu.Cas.Util.User user;
        protected string returnedOpenID = null;
        

        protected void Page_Load(object sender, EventArgs e)
        {
            WebUtils.CheckLoggedIn(Session, Response, Request);
            wsid = (long)Session["USER"];
            lmessage = Request.Params["lmessage"];
            pmessage = Request.Params["pmessage"];

            user = null;

            CasUsers cu = new CasUsers();

            IAuthenticationResponse response = null;
            if (ConfigurationManager.AppSettings["OpenID"]  == "true")
            {
                OpenIdRelyingParty openid = new OpenIdRelyingParty();
                response = openid.GetResponse();
            }
            if (response != null)
            {
                try
                {
                    switch (response.Status)
                    {
                        case AuthenticationStatus.Authenticated:
                            returnedOpenID = response.ClaimedIdentifier.ToString();
                            break;
                        case AuthenticationStatus.Canceled:
                        case AuthenticationStatus.Failed:
                        default:
                            lmessage = "OpenID authentication failed.";
                            break;
                    }
                }
                catch (Exception ex)
                {
                    lmessage = "OpenID authentication failed. " + ex.Message;
                }
            }

            if (Request.Params["LoginGoogle.x"] != null || Request.Params["LoginYahoo.x"] != null || Request.Params["LoginVAO.x"] != null || Request.Params["Name"] == null)
            { // not submitted yet
                // lookup other details
                try
                {
                    User[] users = cu.FindUser(edu.jhu.Cas.Util.ID.SERVICE_ID, "WEBSERVICESID=" + Session["USER"]);
                    if (users == null)
                    {
                        lmessage = "There is a problem with your session - please login and try again.";
                    }
                    else
                    {
                        user = users[0];
                        Session["THEUSER"] = user;
                    }
                }
                catch (Exception ex)
                {
                    lmessage = ex.Message;
                }
                if (user == null)
                {
                    Response.Redirect("ChangeDetails.aspx?lmessage=" + lmessage);
                }
            }
            else
            {
                string pass = Request.Params["newpassword"];
                string cpass = Request.Params["confirmpassword"];
                if (pass != null && cpass != null)
                {
                    if (pass != cpass)
                    {
                        Response.Redirect("ChangeDetails.aspx?pmessage=The password fields are not the same.");
                    }
                    else
                    {
                        //do the change
                        try
                        {
                            // need to pack user
                            user = (User)Session["THEUSER"];
                            bool isvis = user.GVisible;
                            string privMes = "";
                            if (isvis) privMes = "Your name remains visible to all other users in the group screen.";
                            else privMes = "Your name remains invisible to all other users in the group screen.";

                            if (Request.Params["gvisible"] == null && isvis)
                            {// get rid of it
                                user.GVisible = false;
                                privMes = "Your name will no longer be visible to all other users in the group screen.";
                            }
                            if (Request.Params["gvisible"] != null && !isvis)
                            { // add it 
                                user.GVisible = true;
                                privMes = "Your name will now be visible to all other users in the group screen.";
                            }
                            user.UserID = Request.Params["userid"];
                            user.Name = Request.Params["name"];
                            user.Email = Request.Params["email"];
                            if (Request.Params["newpassword"] != null && Request.Params["newpassword"].Length > 0)
                            {
                                user.PWEncrypted = Request.Params["newpassword"];
                            }
                            else user.PWEncrypted = null;
                            user.EmailLevel = Convert.ToInt32(Request.Params["emaillevel"]);
                            user.LastModified = DateTime.Now;
                            if (ConfigurationManager.AppSettings["OpenID"] == "true")
                            {
                                user.OpenID = Request.Params["openid"].Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                            }
                            bool ok = cu.UpdateAccount(wsid, user);
                            if (ok)
                            {
                                Response.Redirect("default.aspx?lmessage=Your account was updated sucessfully.");
                            }
                            else
                            {
                                lmessage = "There was a problem updating your account.";
                            }
                        }
                        catch (Exception ex)
                        {
                            lmessage = ex.Message;
                        }
                    }
                }
            }
        }

        protected void LoginButton_Click(object sender, EventArgs e)
        {
            string discovery = "";

            switch (((ImageButton)sender).CommandName)
            {
                case "LoginGoogle":
                    discovery = OPENID.DISCOVERY_GOOGLE;
                    break;
                case "LoginYahoo":
                    discovery = OPENID.DISCOVERY_YAHOO;
                    break;
                case "LoginVAO":
                    discovery = OPENID.DISCOVERY_VAO;
                    break;
                default:
                    break;
            }

            using (OpenIdRelyingParty openid = new OpenIdRelyingParty())
            {
                IAuthenticationRequest request = openid.CreateRequest(discovery);
                request.RedirectToProvider();
            }
        }

        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());
        }
    }
}