using System;
using System.Collections.Generic;
using System.Linq;
using Pixiview.UI;
using Pixiview.Utils;
using Xamarin.Forms;

namespace Pixiview.Illust
{
    public partial class UserIllustPage : IllustUserDataCollectionPage
    {
        private const int STEP = 48;

        public static readonly BindableProperty UserIconProperty = BindableProperty.Create(
            nameof(UserIcon), typeof(ImageSource), typeof(UserIllustPage));

        public ImageSource UserIcon
        {
            get => (ImageSource)GetValue(UserIconProperty);
            set => SetValue(UserIconProperty, value);
        }

        public IIllustItem UserItem { get; }

        private int startIndex;
        private int nextIndex;
        private string[] illustIds;

        public UserIllustPage(IIllustItem item)
        {
            UserItem = item;
            UserIcon = item.ProfileImage;

            Resources.Add("cardView", GetCardViewTemplate(true));
            InitializeComponent();

            startIndex = -1;
            nextIndex = 0;
        }

        protected override bool IsAutoReload => false;
        protected override ActivityIndicator LoadingIndicator => activityLoading;

        protected override IEnumerable<IllustItem> DoGetIllustList(IllustUserData data)
        {
            if (data.body == null)
            {
                return null;
            }
            return data.body.works.Select(i => i.Value?.ConvertToItem());
        }

        protected override IllustUserData DoLoadIllustData(bool force)
        {
            var userId = UserItem.UserId;
            if (startIndex < 0)
            {
                var init = Stores.LoadIllustUserInitData(userId);
                if (init == null || init.body == null)
                {
                    return null;
                }
                illustIds = init.body.illusts.Keys.OrderByDescending(i => int.TryParse(i, out int id) ? id : -1).ToArray();
#if DEBUG
                App.DebugPrint($"user has ({illustIds.Length}) illusts.");
#endif
                startIndex = 0;
            }

            if (illustIds == null || startIndex >= illustIds.Length)
            {
                return null;
            }
            var ids = illustIds.Skip(startIndex).Take(STEP).ToArray();
            var data = Stores.LoadIllustUserData(userId, ids, startIndex == 0);
            nextIndex = startIndex + STEP;
            if (ids.Length == 0 || nextIndex >= illustIds.Length)
            {
                // done
#if DEBUG
                App.DebugPrint($"download completed: {startIndex}");
#endif
                startIndex = nextIndex;
            }
            return data;
        }

        private void FlowLayout_MaxHeightChanged(object sender, HeightEventArgs e)
        {
            SetOffset(e.ContentHeight - scrollView.Bounds.Height - SCROLL_OFFSET);
        }

        protected override bool CheckRefresh()
        {
            if (nextIndex > startIndex)
            {
                startIndex = nextIndex;
                return true;
            }
            return false;
        }

        private void ScrollView_Scrolled(object sender, ScrolledEventArgs e)
        {
            var y = e.ScrollY;
            OnScrolled(y);
        }

        private async void Refresh_Clicked(object sender, EventArgs e)
        {
            if (IsLoading)
            {
                return;
            }
            await ScrollToTopAsync(scrollView);
            startIndex = -1;
            nextIndex = 0;
            illustIds = null;
            StartLoad(true);
        }
    }
}
