using System;
using System.Management.Automation;
using PSInfisicalAPI.Connections;
using PSInfisicalAPI.Models;
using PSInfisicalAPI.Tags;

namespace PSInfisicalAPI.Cmdlets
{
    [Cmdlet(VerbsCommon.Get, "InfisicalTag", DefaultParameterSetName = "List")]
    [OutputType(typeof(InfisicalTag))]
    public sealed class GetInfisicalTagCmdlet : InfisicalCmdletBase
    {
        [Parameter(ParameterSetName = "Single", Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)]
        [Alias("Slug", "Id")]
        public string TagSlugOrId { get; set; }

        [Parameter(Mandatory = true)] public string ProjectId { get; set; }

        protected override void ProcessRecord()
        {
            try
            {
                InfisicalConnection connection = InfisicalSessionManager.RequireCurrent();
                InfisicalTagClient client = new InfisicalTagClient(HttpClient, Logger);

                if (string.Equals(ParameterSetName, "Single", StringComparison.Ordinal))
                {
                    InfisicalTag tag = client.Retrieve(connection, ProjectId, TagSlugOrId);
                    if (tag != null)
                    {
                        WriteObject(tag);
                    }

                    return;
                }

                InfisicalTag[] tags = client.List(connection, ProjectId);
                Logger.Information("Get-InfisicalTag", string.Concat("Returned ", tags.Length.ToString(System.Globalization.CultureInfo.InvariantCulture), " tag(s)."));
                foreach (InfisicalTag tag in tags)
                {
                    WriteObject(tag);
                }
            }
            catch (Exception exception)
            {
                ThrowTerminatingForException("GetInfisicalTagCmdlet", "GetTag", exception);
            }
        }
    }
}
