using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Pixiview.Utils;
using Xamarin.Forms;

namespace Pixiview.Illust
{
    public partial class MainPage : IllustDataCollectionPage
    {
        public static readonly BindableProperty KeywordsProperty = BindableProperty.Create(
            nameof(Keywords), typeof(string), typeof(MainPage));

        public string Keywords
        {
            get => (string)GetValue(KeywordsProperty);
            set => SetValue(KeywordsProperty, value);
        }

        private double lastScrollY = double.MinValue;
        private ScrollDirection scrollDirection = ScrollDirection.Stop;

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

#if __IOS__
            searchBar.BackgroundColor = Color.Transparent;
#else
            searchBar.SetDynamicResource(SearchBar.TextColorProperty, UI.Theme.ThemeBase.TextColor);
            searchBar.SetDynamicResource(SearchBar.PlaceholderColorProperty, UI.Theme.ThemeBase.SubTextColor);
            searchBar.SetDynamicResource(BackgroundColorProperty, UI.Theme.ThemeBase.WindowColor);
#endif
        }

        protected override bool IsRedirectLogin => true;
        protected override ActivityIndicator LoadingIndicator => activityLoading;
        protected override double IndicatorMarginTop => 66;

        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            searchBar.Margin = PageTopMargin;
            panelBar.Margin = PanelTopMargin;
        }

#if __IOS__
        public override void OnOrientationChanged(bool landscape)
        {
            base.OnOrientationChanged(landscape);

            AnimateToMargin(searchBar, PageTopMargin);
            AnimateToMargin(panelBar, PanelTopMargin);
        }
#endif

        protected override IEnumerable<IllustItem> DoGetIllustList(IllustData data)
        {
            if (data.body == null)
            {
                return null;
            }
            return data.body.page.follow.Select(i =>
                data.body.thumbnails.illust.FirstOrDefault(l => l.illustId == i.ToString())?.ConvertToItem());
        }

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

        private async void Refresh_Clicked(object sender, EventArgs e)
        {
            if (IsLoading)
            {
                return;
            }
            await ScrollToTopAsync(scrollView);
            StartLoad(true);
        }

        private void SearchBar_SearchButtonPressed(object sender, EventArgs e)
        {
            var key = Keywords;
            if (key != null)
            {
                key = key.Trim().ToLower();
            }

            if (!string.IsNullOrEmpty(key))
            {
                Task.Run(() => App.OpenUrl(new Uri("pixiview://example.com/artworks/" + key)));
            }
        }

#if __IOS__
        private const int searchBarHeight = 50;
#else
        private const int searchBarHeight = 40;
#endif

        private void ScrollView_Scrolled(object sender, ScrolledEventArgs e)
        {
            var y = e.ScrollY;
            if (y > lastScrollY)
            {
                // down
                if (scrollDirection != ScrollDirection.Down && y > searchBarHeight - topOffset)
                {
                    scrollDirection = ScrollDirection.Down;
                    if (searchBar.IsFocused)
                    {
                        searchBar.Unfocus();
                    }
                    ViewExtensions.CancelAnimations(searchBar);
                    ViewExtensions.CancelAnimations(panelBar);
                    searchBar.TranslateTo(0, -searchBarHeight, easing: Easing.CubicIn);
                    panelBar.TranslateTo(0, -searchBarHeight, easing: Easing.CubicIn);
                }
            }
            else
            {
                // up
                if (scrollDirection != ScrollDirection.Up)
                {
                    scrollDirection = ScrollDirection.Up;
                    ViewExtensions.CancelAnimations(searchBar);
                    ViewExtensions.CancelAnimations(panelBar);
                    searchBar.TranslateTo(0, 0, easing: Easing.CubicOut);
                    panelBar.TranslateTo(0, 0, easing: Easing.CubicOut);
                }
            }
            lastScrollY = y;
        }
    }
}
