using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Pixiview.Utils;

namespace Pixiview.Illust
{
    public partial class RecommendsPage : IllustDataCollectionPage
    {
        public bool ByUser { get; set; }

        public RecommendsPage()
        {
            Resources.Add("cardView", GetCardViewTemplate());
            InitializeComponent();
        }

        public override void OnLoad()
        {
            StartLoad();
        }

        public override void OnUnload()
        {
            Illusts = IllustCollection.Empty;
            loaded = false;
        }

        protected override IEnumerable<IllustItem> DoGetIllustList(IllustData data, ICommand command)
        {
            if (ByUser)
            {
                return data.body.page.recommendUser.SelectMany(i => i.illustIds)
                    .Select(id =>
                    {
                        var item = data.body.thumbnails.illust.FirstOrDefault(l => l.illustId == id)?.ConvertToItem();
                        if (item != null)
                        {
                            item.IllustTapped = command;
                        }
                        return item;
                    });
            }
            else
            {
                return data.body.page.recommend.Select(id =>
                {
                    var item = data.body.thumbnails.illust.FirstOrDefault(l => l.illustId == id)?.ConvertToItem();
                    if (item != null)
                    {
                        item.IllustTapped = command;
                    }
                    return item;
                });
            }
        }

        protected override IllustData DoLoadIllustData(bool force)
        {
            return Stores.LoadIllustData(force);
        }

        private void Refresh_Clicked(object sender, EventArgs e)
        {
            if (Loading)
            {
                return;
            }
            StartLoad(true);
        }
    }
}
