using Sandbox.ModAPI.Ingame;
using System.Collections.Generic;
using VRage.Game.ModAPI.Ingame.Utilities;

namespace IngameScript
{
    partial class Program
    {
        public class SequenceableDoor : ISequenceable
        {
            public bool Running { get; private set; } = false;
            public int Step { get; set; }

            public bool DeployOpen { get; set; }
            public bool LockOpen { get; set; }
            public bool LockClosed { get; set; }

            private IMyDoor _door;

            public SequenceableDoor(
                Program _program,
                IMyDoor door,
                string sectionName)
            {
                _door = door;

                MyIni ini = _program.Ini;
                ini.TryParse(door.CustomData);
                DeployOpen = ini.Get(sectionName, "deployOpen").ToBoolean(true);
                LockOpen = ini.Get(sectionName, "lockOpen").ToBoolean(true);
                LockClosed = ini.Get(sectionName, "lockClosed").ToBoolean(true);
                Step = ini.Get(sectionName, "step").ToInt32(0);
            }

            public IEnumerator<bool> Run(bool deploy)
            {
                if (Running) yield break;
                Running = true;

                if (deploy && DeployOpen || !deploy && !DeployOpen)
                {
                    foreach (bool tick in _openDoor()) yield return true;
                }
                else
                {
                    foreach (bool tick in _closeDoor()) yield return true;
                }
                Running = false;
            }

            public IEnumerable<bool> _openDoor()
            {
                _door.Enabled = true;
                _door.OpenDoor();
                while (_door.Status != DoorStatus.Open) yield return true;
                if (LockOpen)
                {
                    _door.Enabled = false;
                }
            }

            public IEnumerable<bool> _closeDoor()
            {
                _door.Enabled = true;
                _door.CloseDoor();
                while (_door.Status != DoorStatus.Closed) yield return true;
                if (LockClosed)
                {
                    _door.Enabled = false;
                }
            }
        }
    }
}