{$EVENT evtMissionStart:OnMissionStart_Rebuild}
{$EVENT evtTick:OnTick_Rebuild}

type HouseData = record
	owner: integer;
	houseType: TKMHouseType;
    position: TKMPoint;
  end; 

var aiPlayersHousesArray: array of HouseData;

function AddElementToHouseDataArray(A: array of HouseData; value: HouseData): array of HouseData;
begin
	SetLength(A, Length(A) + 1);
	A[High(A)] := value;
	Result := A;
end;	

function GetHouseDataIndexByPosition(A: array of HouseData; position: TKMPoint): integer;
var i: integer;
var returnValue: integer;
begin
	returnValue := -1;
	for i := 0 to Length(A) - 1 do
		begin
			if ((A[i].position.X = position.X) and (A[i].position.Y = position.Y)) then
				begin
					returnValue := i;
					Break;
				end;
		end;
	Result := returnValue;
end;

procedure OnMissionStart_Rebuild;
var houseData: HouseData;
var playerHouseIds: array of integer;
var i,j: integer;
begin
	for i := 0 to States.StatPlayerCount() - 1 do
		begin
			if(States.PlayerIsAI(i)) then
				begin
					playerHouseIds := States.PlayerGetAllHouses(i);
					for j := 0 to Length(playerHouseIds) - 1 do
						begin
							houseData.owner := i;
							houseData.houseType := States.HouseTypeEx(playerHouseIds[j]);
							houseData.position := States.HousePosition(playerHouseIds[j]);
							aiPlayersHousesArray := AddElementToHouseDataArray(aiPlayersHousesArray, houseData);
						end;
				end;
		end;
end;

procedure OnTick_Rebuild;
var i: integer;
var houseIndex: integer;
begin
	if States.GameTime mod 100 = 0 then
		begin
			for i := 0 to Length(aiPlayersHousesArray) - 1 do
				begin
					if(States.HouseAt(aiPlayersHousesArray[i].position.X,aiPlayersHousesArray[i].position.Y) = -1) then
						begin
							houseIndex := GetHouseDataIndexByPosition(aiPlayersHousesArray,aiPlayersHousesArray[i].position);
							Actions.PlanAddHouseEx(aiPlayersHousesArray[houseIndex].owner,aiPlayersHousesArray[houseIndex].houseType,aiPlayersHousesArray[houseIndex].position.X,aiPlayersHousesArray[houseIndex].position.Y);
						end;
				end;
		end;
end;