// Copyright © 2017-2018 Atomic Software, LLC. All Rights Reserved.
// See LICENSE.md for full license information.

using Atom.Core.Diagnostics;
using Atom.Core.Game;
using Atom.Core.Game.GameObjects.Characters;
using Atom.Core.Networking;
using Atom.Core.SQL;

namespace Atom.WorldManagerServer.Services
{
    internal static class AccountService
    {
        internal static bool LoadAccount(Client client, string userName)
        {
            // Load the account information first.
            using (var p_User_GetUserNo = new StoredProcedure("Account.dbo.p_User_GetUserNo", Program.ServerInstance.ODBCConnection))
            {
                p_User_GetUserNo.AddParameter("userID", userName, 20);
                p_User_GetUserNo.AddOutput<int>("nUserNo");
                p_User_GetUserNo.AddOutput<int>("nRet");

                p_User_GetUserNo.Run();

                var UserNo = p_User_GetUserNo.GetOutput<int>("nUserNo");
                var Ret = p_User_GetUserNo.GetOutput<int>("nRet");

                if (Ret != 0)
                {
                    return false;
                }

                client.Account = new Account
                {
                    UserNo = UserNo,
                    Username = userName
                };
            }

            // Load the account's characters second.
            using (var p_Char_GetListOfUserChar = new StoredProcedure("p_Char_GetListOfUserChar", Program.ServerInstance.ODBCConnection))
            {
                p_Char_GetListOfUserChar.AddParameter("nUserNo", client.Account.UserNo);

                using (var Reader = p_Char_GetListOfUserChar.RunReader())
                {
                    if (!Reader.HasRows)
                    {
                        // The account was loaded, there just aren't any characters.
                        return true;
                    }

                    while (Reader.Read())
                    {
                        var CharNo = Reader.GetInt32(0);

                        if (!CharacterService.LoadCharacter(CharNo, out SimpleCharacter Character))
                        {
                            Log.CriticalError($"Failed to load a character for {client.Account.Username}");
                            continue;
                        }

                        client.Account.Characters.Add(Character);
                    }
                }
            }

            return true;
        }
    }
}
