﻿using Alfred.Inputs;
using Alfred.IO;
using Alfred.Models;
using Oakton;
using RestSharp;
using System;

namespace Alfred.Commands
{
    [Description("Lease a device", Name = "lease-device")]
    public sealed class LeaseDeviceCommand : BaseCommand<LeaseDeviceInput>
    {
        private static readonly string LeasesUri = "/api/leases/";
        private static readonly string TypesUri = "/api/types/";

        private readonly IConsole _console;

        public LeaseDeviceCommand()
            : this(new DefaultConsole(), DefaultFactory)
        {
        }

        public LeaseDeviceCommand(IConsole console, Func<Uri, IRestClient> restClientFactory)
            : base(restClientFactory)
        {
            _console = console ?? throw new ArgumentNullException(nameof(console));
        }

        public override bool Execute(LeaseDeviceInput input)
        {
            if (input == null) throw new ArgumentNullException(nameof(input));

            var typeId = GetTypeId(
                new Uri(input.UrlFlag, TypesUri),
                input.Type);

            if (string.IsNullOrEmpty(typeId))
            {
                _console.Error("Unknown type name");
                return false;
            }

            var response = Post<LeaseDeviceResponse>(
                new Uri(input.UrlFlag, LeasesUri),
                new LeaseDeviceRequest
                {
                    Minutes = input.Minutes,
                    TypeId = typeId
                });

            if (response == null || response.Error)
            {
                _console.Error(response?.Message ?? "Error");
                return false;
            }

            _console.Write($"OK: Device {response.DeviceName} ({response.DeviceIPAddress}) leased.");
            return true;
        }
    }
}
