using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Gallery.Util;
using Gallery.Util.Interface;
using Gallery.Util.Model;
using Xamarin.Forms;

namespace Gallery.Sources.Yandere
{
    public class GallerySource : GallerySourceBase
    {
        public override string Name => "Yande.re";
        public override string Route => "yandere";
        public override string FlyoutIconKey => "Yandere";
        public override string HomePage => "https://yande.re";

        public override async Task<IEnumerable<GalleryItem>> GetRecentItemsAsync(int page)
        {
            var url = $"https://yande.re/post?page={page}";
            var (result, error) = await NetHelper.RequestObject<YandereItem[]>(url, contentHandler: ContentHandler);

            if (result == null || !string.IsNullOrEmpty(error))
            {
                Log.Error("yandere.content.load", $"failed to load content array, error: {error}");
                return null;
            }

            var items = new GalleryItem[result.Length];
            for (var i = 0; i < items.Length; i++)
            {
                var y = result[i];
                var item = new GalleryItem(y.id)
                {
                    Tags = y.tags?.Split(' '),
                    CreatedTime = y.created_at.ToLocalTime(),
                    UpdatedTime = y.updated_at.ToLocalTime(),
                    UserId = y.creator_id.ToString(),
                    UserName = y.author,
                    Source = Route,
                    SourceUrl = y.source,
                    PreviewUrl = y.preview_url,
                    RawUrl = y.file_url,
                    Width = y.width,
                    Height = y.height
                };
                items[i] = item;
            }
            return items;
        }

        private string ContentHandler(string content)
        {
            var regex = new Regex(@"Post\.register\((\{.+\})\)\s*$", RegexOptions.Multiline);
            var matches = regex.Matches(content);
            var array = new string[matches.Count];
            for (var i = 0; i < array.Length; i++)
            {
                array[i] = matches[i].Groups[1].Value;
            }
            return $"[{string.Join(',', array)}]";
        }

        public override void SetCookie()
        {
            throw new NotImplementedException();
        }

        public override void InitDynamicResources(string family, ResourceDictionary light, ResourceDictionary dark)
        {
            var icon = new FontImageSource
            {
                FontFamily = family,
                Glyph = "\uf302",
                Size = 18.0
            };
            light.Add(FlyoutIconKey, icon);
            dark.Add(FlyoutIconKey, icon);
        }
    }
}