using System;
using System.Collections.Generic;
using System.ComponentModel;
using Xamarin.Forms;
using TheGameExtreme.model.@event;
using TheGameExtreme.viewmodel;
using SkiaSharp;
using System.IO;
using System.Reflection;
using SkiaSharp.Views.Forms;
using TouchTracking;
using Xamarin.Essentials;

namespace TheGameExtreme.view
{
    // Learn more about making custom code visible in the Xamarin.Forms previewer
    // by visiting https://aka.ms/xamarinforms-previewer
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        private bool isFirst = true;
        private Main viewmodel;
        private List<SKRect> stacks = new List<SKRect>();
        Button button;
        List<string> playersNames;


        TouchManipulationBitmap bitmap;
        List<TouchManipulationBitmap> bitmapCollection = new List<TouchManipulationBitmap>();
        Dictionary<long, TouchManipulationBitmap> bitmapDictionary = new Dictionary<long, TouchManipulationBitmap>();



        public MainPage(List<string> playersNames)
        {
            this.playersNames = playersNames;

            InitializeComponent();
            NavigationPage.SetHasNavigationBar(this, false);

            //Assembly assembly = GetType().GetTypeInfo().Assembly;

            ////string[] resourceIDs = assembly.GetManifestResourceNames();
            //string resourceID = "TheGameExtreme.Media.thegame.jpg";

            //SKPoint position = new SKPoint(100, (float)(DeviceDisplay.MainDisplayInfo.Height - 0.2 * DeviceDisplay.MainDisplayInfo.Height));

            //for (int i = 0; i < 8; i++)
            //{
            //    using (Stream stream = assembly.GetManifestResourceStream(resourceID))
            //    {
            //        SKBitmap bitmap = SKBitmap.Decode(stream).Resize(new SKImageInfo(225, 225), SKFilterQuality.High);

            //        bitmapCollection.Add(new TouchManipulationBitmap(bitmap)
            //        {
            //            Matrix = SKMatrix.MakeTranslation(position.X, position.Y - bitmap.Height),
            //        });
            //        position.X += bitmap.Width + 50;
            //    }
            //}


            //stacks.Add(checkbox0);
            //stacks.Add(checkbox1);
            //stacks.Add(checkbox2);
            //stacks.Add(checkbox3);
            //button.Text = "Retry";
            //button.Clicked += retry;

            viewmodel = new Main(playersNames);

            //viewmodel.BindingChanged += OnBindingChanged;

            //viewmodel.PlayerChanged += OnPlayerChanged;

            viewmodel.AlertChanged += OnAlertChanged;

            pseudo.SetBinding(Label.TextProperty, new Binding("Pseudo", source: viewmodel));

            InflateHand();
        }


        private void OnAlertChanged(object sender, EventArgs args)
        {
            if (viewmodel.Alert != null)
            {
                DisplayAlert("", viewmodel.Alert, "OK");
                viewmodel.Alert = null;
            }
        }



        public void OnCanvasViewPaintSurface(object sender, SKPaintSurfaceEventArgs args) // Faire plusieurs canvas
        {

            SKCanvas canvas = args.Surface.Canvas;
            canvas.Clear();

            foreach (TouchManipulationBitmap bitmap in bitmapCollection)
            {
                bitmap.Paint(canvas);
                

            }
        }

        public void OnTouchEffectAction(object sender, TouchActionEventArgs args)
        {
            // Convert Xamarin.Forms point to pixels
            TouchTrackingPoint pt = args.Location;
            SKPoint point =
                new SKPoint((float)(canvasView.CanvasSize.Width * pt.X / canvasView.Width),
                            (float)(canvasView.CanvasSize.Height * pt.Y / canvasView.Height));

            switch (args.Type)
            {
                case TouchActionType.Pressed:
                    for (int i = bitmapCollection.Count - 1; i >= 0; i--)
                    {
                        TouchManipulationBitmap bitmap = bitmapCollection[i];

                        if (bitmap.HitTest(point))
                        {
                            // Move bitmap to end of collection
                            bitmapCollection.Remove(bitmap);
                            bitmapCollection.Add(bitmap);

                            // Do the touch processing
                            bitmapDictionary.Add(args.Id, bitmap);
                            bitmap.ProcessTouchEvent(args.Id, args.Type, point);
                            canvasView.InvalidateSurface();
                            break;
                        }
                    }
                    break;

                case TouchActionType.Moved:
                    if (bitmapDictionary.ContainsKey(args.Id))
                    {
                        TouchManipulationBitmap bitmap = bitmapDictionary[args.Id];
                        bitmap.ProcessTouchEvent(args.Id, args.Type, point);
                        canvasView.InvalidateSurface();
                    }
                    break;

                case TouchActionType.Released:
                case TouchActionType.Cancelled:
                    if (bitmapDictionary.ContainsKey(args.Id))
                    {
                        TouchManipulationBitmap bitmap = bitmapDictionary[args.Id];
                        bitmap.ProcessTouchEvent(args.Id, args.Type, point);
                        bitmapDictionary.Remove(args.Id);
                        canvasView.InvalidateSurface();
                    }
                    break;
            }
        }

        public void OnTouchModePickerSelectedIndexChanged(object sender, EventArgs args)
        {
            if (bitmap != null)
            {
                Picker picker = (Picker)sender;
                bitmap.TouchManager.Mode = (TouchManipulationMode)picker.SelectedItem;
                
            }
        }









<<<<<<< HEAD
        //private void OnPlayerChanged(object sender, PlayerChangedEventArgs args)
        //{
        //    inflateHand();
        //}
=======
        private void OnPlayerChanged(object sender, PlayerChangedEventArgs args)
        {
            InflateHand();
        }
>>>>>>> 63f000719bc49139482f85661607797f88afe093

        private void InflateHand()
        {
            //Hand.Children.Clear();
            //for (int i = 0; i < viewmodel.CurrentHand.Count; i++)
            //{
            //    Button card = new Button();
            //    card.Text = viewmodel.CurrentHand[i].Value.ToString();
            //    card.Clicked += played;
            //    Hand.Children.Add(card);
            //}


            bitmapCollection.Clear();

            Assembly assembly = GetType().GetTypeInfo().Assembly;

            string resourceID = "TheGameExtreme.Media.thegame.jpg";

            SKPoint position = new SKPoint(100, (float)(DeviceDisplay.MainDisplayInfo.Height - 0.2 * DeviceDisplay.MainDisplayInfo.Height));

            for (int i = 0; i < viewmodel.CurrentHand.Count; i++)
            {
                using (Stream stream = assembly.GetManifestResourceStream(resourceID))
                {
                    SKBitmap bitmap = SKBitmap.Decode(stream).Resize(new SKImageInfo(225, 225), SKFilterQuality.High);

                    bitmapCollection.Add(new TouchManipulationBitmap(bitmap)
                    {
                        Matrix = SKMatrix.MakeTranslation(position.X, position.Y - bitmap.Height),
                    });
                    position.X += bitmap.Width + 50;
                }
            }
        }

        private void OnBindingChanged(object sender, TopRangeChangedEventArgs args)
        {





            //switch (args.NumStackChanged)
            //{
            //    case 0:
            //        pile0.Text = args.NewTopRangeCard.Value.ToString();
            //        break;
            //    case 1:
            //        pile1.Text = args.NewTopRangeCard.Value.ToString();
            //        break;
            //    case 2:
            //        pile2.Text = args.NewTopRangeCard.Value.ToString();
            //        break;
            //    case 3:
            //        pile3.Text = args.NewTopRangeCard.Value.ToString();
            //        break;
            //}

            //for (int i = 0; i < Hand.Children.Count; i++)
            //{
            //    Button b = Hand.Children[i] as Button;
            //    if (String.Equals(b.Text,args.NewTopRangeCard.Value.ToString()))
            //    {
            //        Hand.Children.RemoveAt(i);
            //        break;
            //    }
            //}
        }

        private void played(object sender, EventArgs args)
        {
            int numStack = 0;
            bool hasFind = false;
            stacks.ForEach(checkbox =>
            {
                //if (checkbox.IsChecked)
                //{
                //    hasFind = true;
                //    if (viewmodel.played(numStack, Convert.ToInt32((sender as Button).Text)))
                //    {
                //        botPanel.Children.Add(button);
                //    }
                //}
                numStack += 1;
            });

            if (!hasFind)
            {
                viewmodel.Alert = "Aucune pile selectionné! Veuillez séléctionner une pile.";
                return;
            }
        }

        //private void radioButton(object sender, EventArgs args)
        //{
        //    if (isFirst)
        //    {
        //        isFirst = false;

        //        stacks.ForEach(checkbox =>
        //        {
        //            if (!checkbox.Equals(sender))
        //            {
        //                checkbox.IsChecked = false;
        //            }
        //        });

        //        isFirst = true;
        //    }
        //}

        private void retry(object sender, EventArgs args)
        {
            viewmodel = new Main(playersNames);

            viewmodel.BindingChanged += OnBindingChanged;

            pseudo.SetBinding(Label.TextProperty, new Binding("Pseudo", source: viewmodel));

            inflateHand();

            //pile0.Text = "1";
            //pile1.Text = "1";
            //pile2.Text = "100";
            //pile3.Text = "100";

            gameOption.Children.Clear();
            gameOption.Children.Add(button);
        }

        private void EndTurn(object sender, EventArgs args)
        {
            if (viewmodel.endTurn())
            {
                button = (Button)gameOption.Children[0];
                gameOption.Children.Clear();
                Button retryButton = new Button();
                retryButton.Text = "Retry";
                retryButton.Clicked += retry;
                gameOption.Children.Add(retryButton);
            }
            else
            {
                inflateHand();
            }
        }

        private async void PlayToHome(object sender, EventArgs args)
        {
            await Navigation.PopToRootAsync();
        }
    }
}
