using System;
using Dominio;
using Infraestructura;
using Newtonsoft.Json;
using ProjectService.Models;
using ProjectService.Services;
using IClientService = ProjectService.Interfaces.IClientService;

namespace ProjectService.Implementations
{
    class ClientService : IClientService
    {
        private readonly Infraestructura.IClientService _clientService;
        private readonly ServiceLocator _serviceLocator = new ServiceLocator();

        public ClientService()
        {
            _clientService = _serviceLocator.Container.GetInstance<Infraestructura.IClientService>();
        }

        public string RegisterClient(string value)
        {
            var client = JsonConvert.DeserializeObject<ClientRequest>(value);
            var model = new ClientRequestModel
            {
                Name = client.Name,
                LastName = client.LastName,
                Identification = new IdentificationType()
            };
            TipoEnum type;
            if (Enum.TryParse(client.IdType, true, out type))
                model.Identification.Type = type;
            model.Identification.Value = client.IdValue;
            var result = _clientService.Register(model);
            var clientResult = new ClientResult
            {
                ClientId = result.ClientId,
                Message = result.Message,
                State = result.State
            };
            return JsonConvert.SerializeObject(clientResult);
        }

        public string GetClient(string id)
        {
            var result = _clientService.GetById(id);
            var resultObject = new ClientModel
            {
                Id = result.Id,
                Name = result.Name,
                LastName = result.LastName,
                IdType = result.IdType.Type.ToString(),
                IdValue = result.IdType.Value
            };
            return JsonConvert.SerializeObject(resultObject, Formatting.None);
        }
    }
}