using System;
using System.Linq;
using System.Windows.Media.Imaging;
using InABox.Core;
using InABox.WPF;

namespace InABox.DynamicGrid
{
    public enum DynamicRowMovement
    {
        Up,
        Down
    }

    public class DynamicRowMovementColumn : DynamicImageColumn
    {
        private readonly BitmapImage downarrow =Wpf.Resources.downarrow.AsBitmapImage();
        private readonly Func<int, int, bool> Swap;
        private readonly BitmapImage uparrow =Wpf.Resources.uparrow.AsBitmapImage();

        public DynamicRowMovementColumn(DynamicRowMovement direction, Func<int, int, bool> swap) : base(r => null)
        {
            Direction = direction;
            Swap = swap;
            Image = GetImage;
            Action = MoveRow;
            Position = DynamicActionColumnPosition.Start;
        }

        public DynamicRowMovement Direction { get; }

        private static bool IsFirst(CoreRow? row)
        {
            return row != null && row.Table.Rows.First() == row; // (row.Index == 0);
        }

        private static bool IsLast(CoreRow? row)
        {
            return row != null && row.Table.Rows.Last() == row; //(row.Index == row.Table.Rows.Count - 1);
        }


        private BitmapImage? GetImage(CoreRow? row)
        {
            if (Direction.Equals(DynamicRowMovement.Up))
                return IsFirst(row) ? null : uparrow;
            return IsLast(row) ? null : downarrow;
        }

        private bool MoveRow(CoreRow? row)
        {
            if (row is null) return false;

            var tgt = row.Index + (Direction.Equals(DynamicRowMovement.Up) ? -1 : 1);
            if (tgt > -1 && tgt < row.Table.Rows.Count)
                return Swap(row.Index, tgt);
            return false;
        }
    }
}