﻿var User = {
    UserName: function()
    {
        return Cookies.Get("UserName");
    },
    ClearCookies: function()
    {
        Cookies.Delete("UserEmail");
        Cookies.Delete("PasswordHash");
        Cookies.Delete("LoggedIn");
        Cookies.Delete("IsRemembered");
        Cookies.Delete("UserName");
        Cookies.Delete("UserSalt");
    },
    Logout: function ()
    {
        User.ClearCookies();
    },
    Login: function (email, password, sessionSalt, onSuccess, onError, rememberMe)
    {
        if (!email) email = Cookies.Get("UserEmail");
        if (!password) password = Cookies.Get("PasswordHash");
        if (!onSuccess) onSuccess = function (){ };
        if (!onError) onError = function (){ };

        //if there was no Cookie this function requires a password and email
        if (!email || !password)
        {
            onError("Email and password required, this user is not remembered");
            return false;
        }

        //do not process the request if the email is invalid
        if (!Validator.IsValidEmail(email))
        {
            onError("Invalid email format");
            return false;
        }

        //We keep the user salt in a cookie but if its gone we request it from the server
        var salt = Cookies.Get("UserSalt");

        //if no cookie, request the salt from the server,
        //the salt is public however, the hashed salt+password
        //is only transmitted upon registration
        if (salt == null)
        {
            User.GetSalt(email,
            login, //success!
            function (msg)
            {
                onError(msg);
            });
        }
        else
        {
            login(salt);
        }


        return true;

        //call the login web method
        function login(userSalt)
        {
            var userHash = Cookies.Get("PasswordHash");

            //if no hash in the cookie we must compute it
            if (userHash == null)
            {
                var shaObj = new jsSHA(password + userSalt);
                userHash = shaObj.getHash("SHA-512", "HEX");
            }

            //compute the session hash which is our authentication
            //token
            var shaObj = new jsSHA(userHash + sessionSalt);
            var hash = shaObj.getHash("SHA-512", "HEX");

            var user =
            {
                email: email,
                hash: hash
            };

            //This is where we actually log in to the site
            CallWebMethod(
                "WebMethods/UserHandler.aspx/logon",
                JSON.stringify(user),

                function (msg)
            {
                var usr = JSON.parse(msg.d);

                if (usr.success == "true")
                {
                    if (rememberMe == true)
                    {
                        Cookies.Add("UserEmail", email, 30);
                        Cookies.Add("PasswordHash", userHash,30);
                        Cookies.Add("UserSalt", userSalt, 30);
                        Cookies.Add("IsRemembered", "true", 30);
                    }

                    Cookies.Add("LoggedIn", "true");
                    Cookies.Add("UserName", usr.userName,30);

                    onSuccess(usr.userName);
                }
                else
                {
                    User.ClearCookies();
                    onError(usr.message);
                }
            },
            function (msg, m2, m3) //failure :(
            {
                User.ClearCookies();
                onError(msg.responseText);
            });
        }
    },

    GetSalt: function (email, onSuccess, onError)
    {
        if (!Validator.IsValidEmail(email))
        {
            onError("Invalid email format");
            return false;
        }

        var user = { email: email };

        CallWebMethod(
            "WebMethods/UserHandler.aspx/GetInitialSalt",
            JSON.stringify(user),
            function (msg)
        {
            onSuccess(msg.d);
        },
                function (msg, m2, m3)
                {
            User.ClearCookies();
            onError(msg.responseText);
        });

        return true;
    },

    Register: function (email, password, userName, onSuccess, onError)
    {
        if (!Validator.IsValidEmail(email))
        {
            onError("Invalid email format");
            return false;
        }

        var user = { email: email };

        CallWebMethod(
            "WebMethods/UserHandler.aspx/GetInitialSalt",
            JSON.stringify(user),
            function (msg)
        {
            var salt = msg.d;

            var shaObj = new jsSHA(password + salt);
            var hash = shaObj.getHash("SHA-512", "HEX");

            var user =
            {
                email: email,
                hash: hash,
                userName: userName
            };

            CallWebMethod(
                    "WebMethods/UserHandler.aspx/RegisterUser",
                    JSON.stringify(user),
                    function (msg)
            {
                Cookies.Add("UserSalt", salt);
                
                onSuccess(msg.d);
            },
                    function (msg, m2, m3)
                    {

                onError(msg.responseText);
            });

        },
            function (msg, m2, m3)
            {
            User.ClearCookies();
            onError(msg.responseText);
        });

        return true;
    },
    IsEmailTaken: function (email, onSuccess, onError)
    {
        if (!Validator.IsValidEmail(email))
        {
            onError("Invalid email format");
            return false;
        }

        var user = { email: email };

        CallWebMethod(
            "WebMethods/UserHandler.aspx/CheckUserEmail",
            JSON.stringify(user),
            function (msg)
        {
            try
            {
                var data = JSON.parse(msg.d);

                onSuccess(data.taken);
            }
            catch (e)
            {
                onError("Server error, unable to parse response to CheckUserEmail");
            }
        },
            function (msg, m2, m3)
        {
            onError(msg.responseText);
        });
    },
    IsLoggedIn: function ()
    {
        return Cookies.Get("LoggedIn") == "true";
    },
    IsRemembered: function ()
    {
        return Cookies.Get("IsRemembered") == "true";
    }



}
