using ExtensiblePortfolioSite.SDK;
using ExtensiblePortfolioSite.SDK.Git;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace GithubPlugin
{
    [Serializable]
    public class GithubUser : IUser
    {
        [JsonInclude]
        [JsonPropertyName("login")]
        public string Name { get; init; }

        [JsonInclude]
        [JsonPropertyName("id")]
        public int Identifier { get; init; }

        [JsonInclude]
        [JsonPropertyName("avatar_url")]
        public string AvatarURL { get; init; }

        [JsonIgnore]
        public GithubProvider Provider { get; internal set; }

        [JsonIgnore]
        IGitProvider IGitObject.Provider => this.Provider;

        public GitReference GetReference()
        {
            return new GitReference(GitReferenceKind.User, $"{Name}");
        }

        public IEnumerable<IRepository> GetUserRepositories()
        {
            var response = Provider.GetAPIResource($"users/{Name}/repos");
            if(response.IsSuccessStatusCode)
            {
                using Stream STM = response.Content.ReadAsStream();
                foreach (GithubRepo repo in Json.Deserialize<GithubRepo[]>(STM) ?? Array.Empty<GithubRepo>())
                {
                    repo.Provider = this.Provider;
                    yield return repo;
                }
            }
        }
    }
}
