local core = require('openmw.core')
local util = require("openmw.util")
local world = require('openmw.world')
local types = require('openmw.types')
local time = require('openmw_aux.time')

--- @param openmw.core#GameObject actor
local function onActorActive(actor)
    if types.NPC.objectIsInstance(actor) and types.NPC.record(actor).name == "Eldafire" then
    
      local round = 0
      local times_end = 10
      local copy_pace = 3*time.second
      
      local clonedRecords = actor -- first actor to come active or targeted object, etc.
        
          stop = time.runRepeatedly(function() 
                          
             round = round + 1              
             
              -- copy jumbo mumbo     
             local used_temp = types.NPC.record(clonedRecords)
             local draft = types.NPC.createRecordDraft({ name = "eldar", template = used_temp})

             local created_record = world.createRecord(draft)
             local new_actor = world.createObject(created_record.id,1)

             local place_direction = clonedRecords.rotation:apply(clonedRecords.position):normalize()
             local place_position = clonedRecords.position + place_direction * -300
                  
                -- teleport the copy
                  new_actor:teleport(clonedRecords.cell, place_position)
                                                        
              --  print(tostring(place_position))
              
              -- replacing to new one
              clonedRecords = new_actor
                  print(round, clonedRecords.id)
              

          if round > times_end then -- ends the cloning
              stop()
          end
                  
        end, copy_pace)  --end of the timer           
  
    end
end

return { engineHandlers = { onActorActive = onActorActive }}