dofile(LockOn_Options.script_path.."Macro_sequencies.lua")
dofile(LockOn_Options.script_path.."command_defs.lua")

local coroutines  = {}
local start_order = 1;
local stop_order  = 2;

function CoroutineResume(index,time_)
local  routine = coroutines[index]
if     routine            == nil or routine.next_event == nil then return false end
local  ret,t   = routine:next_event(time_) 
if     ret == false then
       coroutines[index] = nil
end
return ret,t
end



function sequence_handler(routine,t)
    local stage          = routine.stage or 1
	if  routine.sequence == nil or 
	   #routine.sequence == 0   then
        return false
    end
    local  current_time = routine.sequence[stage].time
    while  math.abs(routine.sequence[stage].time - current_time) < 0.001 do
       dispatch_action(routine.sequence[stage].device,
                       routine.sequence[stage].action,
                       routine.sequence[stage].value)
       stage = stage + 1
       if stage > #routine.sequence then
          return false
       end 
    end
    routine.stage = stage
    local   dt = routine.sequence[routine.stage].time - routine.sequence[routine.stage - 1].time
    return  true, t + dt
end

function check_routine(n_routine,sequence)
    if coroutines[n_routine] ~= nil then
       coroutines[n_routine]:kill_me()
       coroutines[n_routine]  = nil
    else
       coroutines[n_routine]  = coroutine_create(n_routine)
       coroutines[n_routine].next_event = sequence_handler
       coroutines[n_routine].stage      = nil 
       coroutines[n_routine].sequence   = sequence
       coroutines[n_routine]:start(0.3)
    end
end

function kill_routine(n_routine)
    if coroutines[n_routine] ~= nil then
       coroutines[n_routine]:kill_me()
       coroutines[n_routine]  = nil
    end
end

function SetCommand(command,value)
    if track_is_reading() then
        return
    end
	if command == Keys.iCommandEnginesStart then	
		if LockOn_Options.flight.easy_radar then 
		    check_routine(start_order,start_sequence_full)
		else
		    check_routine(start_order,start_sequence_heavy)
		end
	elseif command == Keys.iCommandEnginesStop then
        kill_routine(start_order)
        check_routine(stop_order,stop_sequence_full)
	else
    end
end

function post_initialize()

end

function CockpitEvent(event,params)

end

function release()
  for i,o in pairs(coroutines) do
		if coroutines[i] ~= nil then
		   coroutines[i]:kill_me();
		   coroutines[i] = nil 
		end
  end
end

