using ExtensiblePortfolioSite.SDK.Git;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

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

        [JsonPropertyName("id")]
        public int Identifier { get; private set; }

        [JsonPropertyName("avatar_url")]
        public string AvatarURL { get; private set; }

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

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

        public IEnumerable<IRepository> GetUserRepositories()
        {
            var response = Provider.GetAPIResource($"users/{Name}/repos");
            if(response.IsSuccessStatusCode)
            {
                JsonDocument json = JsonDocument.Parse(response.Content.ReadAsStream());
                List<IRepository> ret = new List<IRepository>(json.RootElement.GetArrayLength());
                foreach(JsonElement repo in json.RootElement.EnumerateArray())
                {
                    ret.Add(JsonSerializer.Deserialize<GithubRepo>(repo)!);
                }
                return ret;
            }
            return new List<IRepository>();
        }
    }
}
