using LeMangeurDEnfants.Core.Entities;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using MonoGame.FourEngine;
using MonoGame.FourEngine.Components;
using MonoGame.FourEngine.Entities;
using System;
using System.Collections.Generic;
using System.Linq;

namespace LeMangeurDEnfants.Core.Scenes
{
    public abstract class CodecScene : Scene
    {
        protected abstract string BackgroundFile { get; }

        private SfxComponent _codecSfx;
        private SfxComponent _newMsgSfx;
        private TextEntity _text;
        private Queue<string> _dialog;

        private TimeSpan _timeToSwitch = TimeSpan.FromSeconds(1);

        public CodecScene()
        {
            AddEntity(new AutoSprite(BackgroundFile, Configuration.InnerResolution));
            AddEntity(_text = new CandaraText
            {
                Position = new Point(50, 100),
            });
            _codecSfx = new SfxComponent(Resources.Sfx.Codec);
            _codecSfx.Play();
            _newMsgSfx = new SfxComponent(Resources.Sfx.NewMsg);
            _dialog = new Queue<string>(GetDialog());
        }

        protected abstract IEnumerable<string> GetDialog();

        protected abstract void OnDialogEnd();

        public override void OnUpdate(UpdateEventArgs args)
        {
            base.OnUpdate(args);
            var next = args.Keyboard.State[Keys.Space].HasClicked
                || args.Keyboard.State[Keys.Enter].HasClicked
                || args.GamePad.State[Buttons.A].HasClicked
                || args.GamePad.State[Buttons.Start].HasClicked;
            if (next) _timeToSwitch = TimeSpan.Zero;
            if (_timeToSwitch > args.DeltaTime)
            {
                _timeToSwitch -= args.DeltaTime;
            }
            else
            {
                _timeToSwitch = TimeSpan.FromSeconds(15);
                if (_dialog.Any())
                {
                    _text.Text = _dialog.Dequeue();
                    _newMsgSfx.Play();
                }
                else
                {
                    OnDialogEnd();
                }
            }
        }

        public override void OnDetach(DrawingSurfaceBase surface)
        {
            base.OnDetach(surface);
            _codecSfx.Dispose();
            _newMsgSfx.Dispose();
        }
    }
}