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

using Atom.Core;
using Atom.Core.Extensions;
using Atom.Core.Game.GameObjects.Characters;
using Atom.Core.Networking;
using Atom.Core.Networking.Messages.Structures.Avatar;
using Atom.WorldManagerServer.Services;
using System;

namespace Atom.WorldManagerServer.Logic
{
    internal sealed class CharacterLogic
    {
        // CGR = Class, Gender, Race
        internal static void CreateCharacter(Client Client, byte Slot, string Name, byte CGR, byte Hair, byte HairColor, byte Face)
        {
            var Class = (CharacterClass) (byte) ((CGR >> 2) & 0x1F);
            var Gender = (Gender) (byte) ((CGR >> 7) & 0x01);
            
            if (Class.GetBaseClass() == CharacterClass.Crusader && !Client.Account.Characters.Exists(Character => Character.Level >= Program.SingleData["ChrLevel_CanCreateSen"]))
            {
                new PROTO_NC_AVATAR_CREATEFAIL_ACK(CreateCharacterFailedErrorCode.LV60REQ).Send(Client);
                return;
            }

            if (CharacterService.IsNameInUse(Name))
            {
                new PROTO_NC_AVATAR_CREATEFAIL_ACK(CreateCharacterFailedErrorCode.NAME_IN_USE).Send(Client);
                return;
            }

            if (Program.HairColorInfo[HairColor] != 0 || Program.HairInfo[Hair] != 0 || Program.FaceInfo[Face] != 0)
            {
                return;
            }

            if (Client.Account.Characters.Count >= 6)
            {
                new PROTO_NC_AVATAR_CREATEFAIL_ACK(CreateCharacterFailedErrorCode.ERROR_MAX_SLOT).Send(Client);
                return;
            }

            if (!Enum.IsDefined(typeof(CharacterClass), (byte) Class) || Class.GetBaseClass() == CharacterClass.None)
            {
                new PROTO_NC_AVATAR_CREATEFAIL_ACK(CreateCharacterFailedErrorCode.WRONG_CLASS).Send(Client);
                return;
            }

            CharacterService.CreateCharacter(Client, Slot, Name, Class, Gender, Hair, HairColor, Face);
        }
    }
}
