using Sandbox.ModAPI.Ingame;
using VRage.Game.ModAPI.Ingame.Utilities;

namespace IngameScript
{
    partial class Program
    {
        public class Warehouse
        {
            public bool Timeout
            {
                get
                {
                    return _timeoutTicks == 0;
                }
            }

            private IMyConveyorSorter _inputSorter;
            private IMyConveyorSorter _outputSorter;
            private IConsole _console;
            private uint _timeoutTicks = 0;

            public Warehouse(IConsole console)
            {
                _console = new PrefixedConsole(console, "warehouse");
            }

            public void Update(int loadingCount)
            {
                if (_timeoutTicks > 0)
                {
                    _timeoutTicks--;
                    if (_timeoutTicks == 0 || loadingCount == 0)
                    {
                        _console.Print("Disabling loading mode and restoring default behavior.");
                        _timeoutTicks = 0;
                        _outputSorter.Enabled = false;
                        _inputSorter.Enabled = true;
                    }
                }
            }

            // A dock has requested loading
            public void StartLoading()
            {
                _console.Print("A dock has requested loading mode.");
                _inputSorter.Enabled = false;
                _outputSorter.Enabled = true;
                _timeoutTicks = 75; // This is approximately 2 minutes.
            }

            public void AddBlock(IMyTerminalBlock block, MyIni ini)
            {
                if (!(block is IMyConveyorSorter))
                {
                    _console.Print($"Ignoring incompatible block '{block.CustomName}'");
                    return;
                }
                switch (ini.Get("dockLoader", "direction").ToString())
                {
                    case "input":
                        _inputSorter = block as IMyConveyorSorter;
                        break;
                    case "output":
                        _outputSorter = block as IMyConveyorSorter;
                        break;
                    default:
                        _console.Print($"Invalid direction for '{block.CustomName}'");
                        break;
                }
            }
        }
    }
}