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

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

            private Program _program;
            private IMyPistonBase _piston;
            private float _deployPosition;
            private float _stowPosition;
            private float _velocity;

            public SequenceablePiston(Program program, IMyPistonBase piston, string sectionName)
            {
                _program = program;
                _piston = piston;

                MyIni ini = _program.Ini;
                ini.TryParse(piston.CustomData);

                _deployPosition = ini.Get(sectionName, "deployPosition").ToSingle(10F);
                _stowPosition = ini.Get(sectionName, "stowPosition").ToSingle(0F);
                _velocity = ini.Get(sectionName, "velocity").ToSingle(5F);
                Step = ini.Get(sectionName, "step").ToInt32(0);
            }

            public IEnumerator<bool> Run(bool deploy)
            {
                if (Running) yield break;
                Running = true;
                _program.Console.Print("DEBUG: Piston Starting");

                float targetValue = _stowPosition;
                float lastValue = -1;
                if (deploy) targetValue = _deployPosition;
                _piston.MoveToPosition(targetValue, _velocity);

                while (lastValue != _piston.CurrentPosition)
//                    Math.Abs(_piston.CurrentPosition - targetValue) > 0.01 ||
                {
                    lastValue = _piston.CurrentPosition;
                    _program.Console.Print(_piston.Status.ToString());
                    yield return true;
                }

                Running = false;
            }
        }
    }
}