LoadTileModels("scripts/tilesets/dungeon_campaign.lua")
Load("campaigns/human/04.sms")

AddTrigger(
   function() return (IfNearUnit("this", ">=", 1, "unit-lothar", "unit-start-location") or
                      IfRescuedNearUnit("this", ">=", 1, "unit-lothar", "unit-start-location")) end, ActionVictory)
AddTrigger(function() return GetPlayerData(GetThisPlayer(), "TotalNumUnits") == 0 end, ActionDefeat)

unit = CreateUnit("unit-start-location", 0, {54, 2})

local function SetupRescue(loading)
   -- wounded units should here become soldiers if healed
   -- lothar should look wounded first, then become himself
   for i,unit in ipairs(GetUnits(4)) do
      local ident = GetUnitVariable(unit, "Ident")
      if ident == "unit-lothar" or ident == "unit-wounded-lothar" then
         if ident == "unit-lothar" then
            TransformUnit(unit, "unit-wounded-lothar")
         end
         local lothar = unit
         AddTrigger(function() return (GetUnitVariable(lothar, "HitPoints") < 1) end, ActionDefeat)
      end

      if not loading then
         SetUnitVariable(unit, "HitPoints", 5)
      end

      if GetUnitVariable(unit, "HitPoints") <= 20 then
         local fired = false
         AddTrigger(
            function() return (not fired) and GetUnitVariable(unit, "HitPoints") > 20 end,
            function()
               fired = true
               local ident = GetUnitVariable(unit, "Ident")
               local p = GetUnitVariable(unit, "Player")
               if ident == "unit-wounded-lothar" then
                  TransformUnit(unit, "unit-lothar")
               else
                  SetPlayerData(p, "Resources", "gold", 400) -- Hack: we need the money to "upgrade"
                  TransformUnit(unit, "unit-footman")
               end
               return true
         end)
      end
   end
end

if GetPlayerData(4, "TotalNumUnits") == 0 then
   -- loading a savegame, the units are not created, yet, so we do it in a trigger
   print("Loading savegame")
   AddTrigger(
      function()
         return true
      end,
      function()
         SetupRescue(true)
         return false
      end
   )
else
   SetupRescue(false)
end

SetStartView(0, 60, 0)
