----gKH Namespace setup ----
gKH = nil;
collectgarbage(); -- force clean up of prior garbage\refs.
gKH = {}; --base api namespace
gKH.SceneGlobals = {}; --scene global storage namespace
gKH.Mounts = {}; -- mount api functions
gKH.Groups = {} --  group api functions
gKH.Mounts.dbglevel = 0 -- determines level of printing to log for diagostics 0 = serious errors only, minimal 1=Basic, 2=verbose

---- end gKH Namespace setup ----

---- globals specific to scene ----
--Scene starts with 224 in the SAG, 256 if counting mags.  *scene is setup in general to test with 174A-1B's.
gKH.SceneGlobals.RemainingRIM174IBs = 150; -- Place to set the number of RIM-174A-IB missles (dbid 3714) remaining to trigger mission change.

--Scene starts with 36 in the SAG, 36 if counting mags.  *provided as just another example.
--To enable either triggering it assign the CheckMunitionsRIM174-IA_3541 action to the existing ScanEvery5second event in addition to the existing one.
gKH.SceneGlobals.RemainingRIM174IAs = 6; -- place to set the number of RIM-174A-IA missles (dbid 3514) remtaining to trigger mission change.

---- end globals specific to scene ----


---- functions ripped from gKHApi\Mounts.lua for this test ----

--Function to count the number of specific munitions on a unit by matching a specific weapon dbid. Optionally including mag storage.
--input: u - a unit wrapper object to act upon.
--input: iWpnDBID  - the weapon's specific dbid to match.
--input: bIncludeMags - optional true|false to include magazines in the counting, defaults to false if missing.
--returns: an interger of or nil 
--requires: none 
function gKH.Mounts.CountUnitWeaponsByDBID(u,iWpnDBID,bIncludeMags)
    local fn = "gKH.Mounts.CountUnitWeaponsByDBID: ";
    if u == nil then print(fn .. "unitwrapper is missing or invalid parameter."); return nil; end
    if ((iWpnDBID == nil) or type(iWpnDBID) ~= 'number') or iWpnDBID < 1 then print(fn .. "iWpnDBID is missing or invalid parameter."); return nil; end
    if ((bIncludeMags == nil) or type(bIncludeMags) ~= 'boolean') then bIncludeMags = false; end

    local counter  = 0; --store return value;
    --check mounts.
    if (u.mounts ~=nil) and #u.mounts > 0 then --do mounts exist
        for _,v in pairs(u.mounts) do -- for each of them
            if(v.mount_weapons ~=nil) and #v.mount_weapons > 0 then --do weapons exist on the mount
                for _,j in pairs(v.mount_weapons) do -- for each of them
                    if j.wpn_dbid == iWpnDBID then -- do they match our wpn database id
                        counter = counter + j.wpn_current; --increase counter by current # on the mount. 
                    end
                end
            end
        end
    else
        if gKH.Mounts.dbglevel > 0 then print(fn .. 'No mounts detected.'); end
    end

    --check mags
    if (u.magazines ~=nil) and #u.magazines > 0 and bIncludeMags == true then --do mags exist and are we counting them?
        for _,v in pairs(u.magazines) do -- for each mag
            if (v.mag_weapons ~=nil) and #v.mag_weapons > 0 then --does the mag have any weapon records?
                for i,j in pairs(v.mag_weapons) do -- for each weapon record
                    if j.wpn_dbid == iWpnDBID then --does it match our wpn database id?  
                        counter = counter + j.wpn_current; --increase counter by current # in the mag. 
                    end
                end
            end
        end
    else
        if gKH.Mounts.dbglevel > 0 then print(fn .. 'No mags detected.'); end
    end

    --check loadout info [for aircraft only]
    if u.type == 'Aircraft' then
        local retval,rtbl;
        retval,rtbl = pcall(ScenEdit_GetLoadout,{unit=u.guid,loadoutid=0});
        if ((retval ==true) and rtbl ~=nil) and rtbl.weapons ~=nil then --do we have valid return loudoutinfo table?
            if #rtbl.weapons > 0 then -- are there weapons?
                for _,v in pairs(rtbl.weapons) do -- for each weapon entry
                    if v.wpn_dbid == iWpnDBID then --does it match our wpn database id?  
                        counter = counter + v.wpn_current; --increase counter by current # in the mag. 
                    end
                end
            end

        else
            if gKH.Mounts.dbglevel > 0 then print(fn .. 'call to GetLoadout on aircraft unit failed.'); end
        end
    else
        if gKH.Mounts.dbglevel > 0 then print(fn .. 'Unit is not an aircraft skipping loadout counting.'); end
    end

    return counter;
end

----end Mounts.lua ---


----functions ripped from gKHApi\Groups.lua for this test ----

--function to return a total number of a given munition that a group of units has, optionally counting mag storage.
-- input: theside - the name of the side the group belongs to
-- input: thegname - the name of the group.
-- input: theweaponid - the weapons's real dbid (not the weapon record number)
-- input: bincludemags - optional true|false to include magazines in the counting. defaults to false if nil. 
-- returns: an interger of 0 or more on success, nil on serious error.
--
-- requires:  gKH.Mounts
function gKH.Groups.CountGroupMunitions(theside,thename,theweaponid,bincludemags)
    local fn = "gKH.Groups.CountGroupMunitions(): ";
    local retval,grp;
    local runningcount = 0;
    local retunit;
    retval,grp = pcall(SE_GetUnit,{side=theside,name=thename});
    if (retval==true) and grp ~=nil then
        local tmpnum;
        for k,v in pairs(grp.group.unitlist) do
            retval,retunit = pcall(ScenEdit_GetUnit,{guid=v});
            if ((retval ==true) and retunit ~=nil) and retunit.name ~= nil then --make sure we have unit.
                tmpnum = gKH.Mounts.CountUnitWeaponsByDBID(retunit,theweaponid,bincludemags);
                if (tmpnum ~=nil) then -- it can return nil on error.
                    runningcount = runningcount + tmpnum;
                else
                    print( fn .. 'Skipping group member. gKH.Mounts.CountUnitWeaponsByDBID() returned nil for unit guid: ' .. tostring(v));
                end
            else
                print( fn .. 'Skipping group member. Could not obtain unit with guid: ' .. tostring(v));
            end
            retval,retunit,tmpnum = false,nil,nil;
        end
    else
        print(string.format('%s Error: Could get not group unit with name: %s  and side: %s',fn,tostring(thename),tostring(theside)));
        return nil;
    end
    grp = nil;
    return(runningcount);
end

---- end Groups.lua ----

---- Scene Specific global functions ----

--Helper function to reassign missions for blue, and disable and hold-fire on missions for red. 
--called by action lua script when missile count <= whatever the set amount.
function gKH.SceneGlobals.HoldFireAndDisableMissions()
    --reassign blue taskforce to hold fire mission.
    local grpunit = SE_GetUnit({side='Blue',name='SAG_1'});
    if grpunit ~=nil then
        ScenEdit_AssignUnitToMission(grpunit.guid,"BLUE_SAG_2");
    end
    --disable red patrol missions and set Mission_1 and Mission_2 settings to hold-fire.
    local doctrine;
    doctrine = ScenEdit_SetDoctrine({side='Red',mission='Mission_1'}, {weapon_control_status_air=2,weapon_control_status_surface=2});
    doctrine = ScenEdit_SetDoctrine({side='Red',mission='Mission_2'}, {weapon_control_status_air=2,weapon_control_status_surface=2});
    local mission;
    for i = 1,2 do  --for each of the 2 missions
        mission = ScenEdit_GetMission('Red','Mission_' .. i);
        if mission ~= nil then 
            mission.isactive = false;
            if mission.unitlist ~=nil then
                local u; --hold unitwrapper 
                for _,v in pairs(mission.unitlist) do
                    u = SE_GetUnit({guid=v}); --get the unit in the list.
                    u:RTB(true);  --trigger rtb
                    u = nil;
                end
            end

           mission = nil --reset for next loop
        end
    end  --end for each mission
end

---- end Scene Specific global functions ----
