-- Handles LUA Artillary arrays
ArtyArray = {}
ArtyReadyArray = {}
isArrayActive = false
isCommandNonActive = true
selectedBatteryindex = 0

--numUnitsArray starts from 1 like all standard LUA arrays, parse as the hook
function initializeArray()
    if isArrayActive then
        for i=1,9 do
            ArtyArray[i] = {}
            ArtyReadyArray[i] = {}
        end
    end
end

-- Handles the naming of a new array
function handleNameArray(index,namingArray)
    count = 0
    if isArrayActive then
        for i, v in ipairs(namingArray) do
            ArtyArray[index][count] = namingArray[i]
            ArtyReadyArray[index][count] = "Yes"
            count = count + 1
        end
    end
end



function drawBasicBatteryHUD(numArrays,xInit,yInit,spacing)
    
    if isArrayActive then
        gr.CurrentFont = gr.Fonts["modGothic"]
        for i=1,numArrays do
            if ArtyArray[i][0] ~= nil then
                if string.find(ArtyArray[i][0], " --Disabled")  then
                    gr.setColor(255,0,0)
                elseif isCommandNonActive == false  then
                    gr.setColor(255,255,0)
                elseif i == selectedBatteryindex then
                    gr.setColor(0,255,50)
                else
                    gr.setColor(255,255,255)
                end
                gr.drawString(ArtyArray[i][0],xInit,(yInit + (i*spacing)))
            end
        end
        if selectedBatteryindex ~= 0 then
            local stringWidth = gr.getStringWidth(ArtyArray[selectedBatteryindex][0]) + 30
            if ArtyArray[selectedBatteryindex][0] ~= nil then
                for i=1,9 do
                    local value = ArtyArray[selectedBatteryindex][i]
                    local selectedShip = "Wow"
                    if value ~= nil then
                        selectedShip = mn.Ships[value]
                    end

                    if ArtyArray[selectedBatteryindex][i] ~= nil then
                        if selectedShip:isValid() == false then
                            gr.setColor(255,0,0)
                            value = value.."  ---Dead"
                        elseif ArtyReadyArray[selectedBatteryindex][i] == "No"  then
                            gr.setColor(255,0,255)
                            if selectedShip.Target:isValid() then
                                value = value.." ---Aquiring Target:  "..selectedShip.Target.Name
                            else
                                value = value.." ---Aquiring Target:  Target Destroyed"
                            end

                        elseif string.find(ArtyReadyArray[selectedBatteryindex][i], "Cooling") then
                            gr.setColor(255,0,255)
                            value = value.."  ---Weapon "..ArtyReadyArray[selectedBatteryindex][i]
                        elseif ArtyReadyArray[selectedBatteryindex][i] == "Firing" then
                            gr.setColor(255,0,255)
                            if selectedShip.Target:isValid() then
                                value = value.."  ---Firing at: "..selectedShip.Target.Name
                            else
                                value = value.." ---Firing at: Target Destroyed"
                            end

                        elseif ArtyReadyArray[selectedBatteryindex][i] == "Yes" then
                            gr.setColor(0,255,0)
                            value = value.."  ---Ready"

                        elseif ArtyReadyArray[selectedBatteryindex][i] == "Disabled" then
                            gr.setColor(255,255,0)
                            value = value.."  ---Offline"
                        end

                        gr.drawString(value,(xInit + stringWidth),(yInit + (i*spacing)))
                    end
                end
            end
        end
    end
end


-- Selects array and allows firing of units within the array
function targetArray(index)
    if isArrayActive and isCommandNonActive then
        if index == 0 then
            selectedBatteryindex = 0
        elseif selectedBatteryindex == 0 then
            if ArtyArray[index][0] ~= nil and string.find(ArtyArray[index][0], " --Disabled") == nil then
                selectedBatteryindex = index
            end
        else
            local artyIndex = selectedBatteryindex
            local ship = ArtyArray[artyIndex][index] 
            if ship ~= nil then
                ship = mn.Ships[ArtyArray[artyIndex][index]]
                if (ship ~= nil and hv.Player.Target:isValid()) then
                    local target = hv.Player.Target
                    if target.Team == mn.Teams["Hostile"] then
                        startTrackingProcess(ship,target,artyIndex,index)
                    end
                end
            end
        end
    end
end

function disableArray(index)
    if isArrayActive and string.find(ArtyArray[index][0], " --Disabled") == nil then
        ArtyArray[index][0] = ArtyArray[index][0].." --Disabled"
        selectedBatteryindex = 0
    end
end

--Enables arrays that have been disabled through the above command
function enableArray(index)
    if isArrayActive and string.find(ArtyArray[index][0], " --Disabled") then
        ArtyArray[index][0] = ArtyArray[index][0]:sub(1, #ArtyArray[index][0] - 11)
    end
end

-- Function disables laser
function DisableLaser(battery,unit)
    if isArrayActive then
        ArtyReadyArray[battery][unit] = "Disabled"
    end
end

--Function activates laser oniy if it is disabled - Return true for success or false for failure
function EnableDisabledLaser(battery,unit)
    if isArrayActive then
        if ArtyReadyArray[battery][unit] == "Disabled" then
            ArtyReadyArray[battery][unit] = "Yes"
            return true
        else
            return false
        end
    end
end



--Only use bools, bad things happen if you don't (well either it'll turn it off or leave it on, don't try it... please)
function switchBatteryScript(bool)
    isArrayActive = bool
end

function switchCommandScript()
    if isArrayActive and isCommandNonActive then
        async.run(function()
            isCommandNonActive = false
            async.await(mn.waitAsync(5))
            isCommandNonActive = true
        end)
    end
end

function fire(int,shipName,targetName)
    if (int == 1) then
        mn.runSEXP("( fire-beam \""..shipName.."\" \"turret01\" \""..targetName.."\")")
    elseif int==2 then
        createCapitalShip()
    end
end

function startTrackingProcess(ship,target,artyIndex,index)
    if isArrayActive then
        if ArtyArray[artyIndex][index] ~= nil and ArtyReadyArray[artyIndex][index] == "Yes" then
            if ship ~= nil and ship:isValid() and ship.Class.Name == "GTSG Mjolnir" then
                ship:giveOrder(ORDER_PLAY_DEAD_PERSISTENT)

                ship.Target = target

                -- Handles the cycle (Funny fact, destroy ships to end process)
                if target:isValid() and target.Team == mn.Teams["Hostile"] then
                    ship = ship.Name
                    async.run(function()
                        if target:isValid() then
                            mn.runSEXP("( lua-RBC-track-target !"..target.Name.."! !"..ship.."! )")
                        end
                        ArtyReadyArray[artyIndex][index] = "No"
                        async.await(mn.waitAsync(10))

                        if ArtyReadyArray[artyIndex][index] == "No" then
                            ArtyReadyArray[artyIndex][index] = "Firing"
                        end

                        if target:isValid() then
                            fire(1,ship,target.Name)
                        end
                        async.await(mn.waitAsync(4))
                        if target:isValid() then
                            fire(1,ship,target.Name)
                        end

                        async.await(mn.waitAsync(4))

                        if target:isValid() then
                            mn.runSEXP("( lua-RBC-stop-tracking !"..ship.."! )")
                        end

                        
                        if ArtyReadyArray[artyIndex][index] == "Firing" then
                            ArtyReadyArray[artyIndex][index] = "Cooling"
                        end

                        for i=160, 1, -1 do
                            if string.find(ArtyReadyArray[artyIndex][index], "Cooling") then
                                ArtyReadyArray[artyIndex][index] = "Cooling "..i.." Seconds Left"
                                async.await(mn.waitAsync(1))
                            end
                        end

                        if string.find(ArtyReadyArray[artyIndex][index], "Cooling") then
                            ArtyReadyArray[artyIndex][index] = "Yes"
                        end
                    end)

                end
            elseif ship.Class.Name == "GTA Charybdis" then
                ship.Target = target

                async.run(function()
                    ArtyReadyArray[artyIndex][index] = "Firing"
                    local shipArray = {}
                    local shipSecondaryArray = {"Turret Deploy Jump."}

                    if target:isValid() then
                        for i=1, 3, 1 do
                            shipArray[i] = createShip("bomber "..i,"GTB Medusa",primaryTerranTable,shipSecondaryArray,nil,ship.Orientation,ba.createVector(math.random(25000,35000),math.random(25000,30000),math.random(25000,30000)),"Friendly",false)
                        end
                    end
                    async.await(mn.waitAsync(60))
                    for i=1, 3, 1 do
                        if shipArray[i]:isValid() then
                            shipArray[i]:clearOrders()
                            shipArray[i]:giveOrder(ORDER_DEPART)
                        end
                        
                    end

                    if ArtyReadyArray[artyIndex][index] == "Firing" then
                        ArtyReadyArray[artyIndex][index] = "Cooling"
                    end

                    for i=180, 1, -1 do
                        if string.find(ArtyReadyArray[artyIndex][index], "Cooling") then
                            ArtyReadyArray[artyIndex][index] = "Cooling "..i.." Seconds Left"
                            async.await(mn.waitAsync(1))
                        end
                    end



                    if string.find(ArtyReadyArray[artyIndex][index], "Cooling") then
                        ArtyReadyArray[artyIndex][index] = "Yes"
                    end
                end)
            end
        end
    end
end