using InABox.Core;
using InABox.WPF;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Microsoft.Xaml.Behaviors.Core;

namespace InABox.DynamicGrid
{
    public class DFVideoControl : DynamicFormFieldControl<DFLayoutVideoField, DFLayoutVideoFieldProperties, byte[], DFLayoutEmbeddedMediaValue>
    {
        private DFLayoutEmbeddedMediaValue _value = null!;

        private Button? _playButton;
        private Button? _pauseButton;
        private Button? _downloadButton;
        private MediaElement _player = null!;
        private Border? _border;
        private Image? _thumbnail;
        private Grid? _contentGrid;
        private Grid? _grid;
        /*Point center;
        int rotation = 90;
        bool firstPlay = true;*/
        private string _tempfilename = null!;

        byte[]? Data;

        protected override FrameworkElement Create()
        {
            _tempfilename = System.IO.Path.ChangeExtension(System.IO.Path.GetTempFileName(),".mp4");
            
            _value = new DFLayoutEmbeddedMediaValue();

            _grid = new Grid();

            _grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
            _grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });
            _grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
            _grid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Auto) });

            _grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            _grid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                
            _border = new Border()
            {
                BorderBrush = new System.Windows.Media.SolidColorBrush(Colors.Gray),
                BorderThickness = new Thickness(0.75),
                Background = new System.Windows.Media.SolidColorBrush(Colors.White),
                Padding = new Thickness(4),
                Margin = new Thickness(0)
            };
            _border.SetGridPosition(0,0,5,1);
            _grid.Children.Add(_border);
            
            _contentGrid = new Grid();
            _contentGrid.RowDefinitions.Add(new RowDefinition() { Height = new GridLength(1, GridUnitType.Star) });
            _contentGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            _border.Child = _contentGrid;
            
            _thumbnail = new Image
            {
                StretchDirection = StretchDirection.DownOnly,
                Source = EmbeddedImageUtilities.CreateEmptyImage()
            };
            _thumbnail.Visibility = Visibility.Visible;
            _thumbnail.SetGridPosition(0, 0, 4, 1);
            _contentGrid.Children.Add(_thumbnail);
            
            _player = new MediaElement
            {
                Stretch = System.Windows.Media.Stretch.Fill,
                Visibility = Visibility.Visible,
                VerticalAlignment = VerticalAlignment.Center,
                HorizontalAlignment = HorizontalAlignment.Center,
                LoadedBehavior = MediaState.Manual,
                Source = new Uri(_tempfilename)
            };
            _player.Visibility = Visibility.Collapsed;
            _player.MediaOpened += (sender, args) =>
            {
                _player.Visibility = Visibility.Visible;
                _thumbnail.Visibility = Visibility.Collapsed;
            };
            _player.MediaEnded += (sender, args) =>
            {
                _player.Visibility = Visibility.Collapsed;
                _thumbnail.Visibility = Visibility.Visible;
                _player.Close();
            };
            _player.SetGridPosition(0, 0, 4, 1);
            _contentGrid.Children.Add(_player);
            
            _playButton = new Button
            {
                Margin = new Thickness(5,0,0,0),
                Content = new Image { Source = Wpf.Resources.play_button.AsBitmapImage(24,24) },
                Command = new ActionCommand(PlayButton_Click),
                Width = 30,
                Height = 30
            };
            _playButton.SetGridPosition(0, 1);
            _grid.Children.Add(_playButton);

            _pauseButton = new Button
            {
                Margin = new Thickness(5,5,0,0),
                Content = new Image { Source = Wpf.Resources.pause_button.AsBitmapImage(32,32) },
                Command = new ActionCommand(PauseButton_Click),
                Width = 30,
                Height = 30
            };
            _pauseButton.SetGridPosition(1, 1);
            _grid.Children.Add(_pauseButton);
            
            _downloadButton = new Button
            {
                Margin = new Thickness(5,5,0,0),
                Content = new Image { Source = ImageUtils.SvgToBitmapImage(Wpf.Resources.download) },
                Command = new ActionCommand(DownloadButton_Click),
                Width = 30,
                Height = 30
            };
            _downloadButton.SetGridPosition(3, 1);
            _grid.Children.Add(_downloadButton);
            
            return _grid;
        }

        private void DownloadButton_Click()
        {
            var dlg = new SaveFileDialog();
            dlg.AddExtension = true;
            dlg.DefaultExt = ".mp4";
            dlg.ShowDialog();
            if (!string.IsNullOrWhiteSpace(dlg.FileName))
            {
                System.IO.File.WriteAllBytes(dlg.FileName, GetValue());
                MessageBox.Show("Success - file saved to: "
                    + System.Environment.NewLine
                    + dlg.FileName);

                var dir = System.IO.Path.GetDirectoryName(dlg.FileName);

                ProcessStartInfo startInfo = new ProcessStartInfo
                {
                    Arguments = dir,
                    FileName = "explorer.exe"
                };
                Process.Start(startInfo);
            }
        }

        private void PauseButton_Click()
        {
            _player.Pause();
        }

        private void PlayButton_Click()
        {  

            if (System.IO.File.Exists(_tempfilename))
            {
                _player.Play();
            }
            else
            {
                DigitalFormDocumentFactory.LoadDocument(_value.ID, (data) =>
                {
                    Dispatcher.BeginInvoke(() =>
                    {
                        System.IO.File.WriteAllBytes(_tempfilename, data);

                        _player.Position = new TimeSpan(0);
                        _player.Play();
                    });
                }); 
            }
        }

        public override DFLayoutEmbeddedMediaValue GetSerializedValue()
        {
            if ((_value.Data?.Any() == true) && (_value.ID == Guid.Empty))
                _value.ID = DigitalFormDocumentFactory.SaveDocument(_value.Data);
            return _value;
        }

        public override void SetSerializedValue(DFLayoutEmbeddedMediaValue value)
        {
            _value = value;
            EmbeddedImageUtilities.LoadImageFromData(_thumbnail, _value.Thumbnail);
        }

        public override byte[] GetValue()
        {
            return Data ?? Array.Empty<byte>();
        }

        public override void SetValue(byte[]? value)
        {
            Data = value;
        }

        protected override bool IsEmpty() => Data is null || Data.Length == 0;
    }
}
