-- Mining & Logging SmartDestroy by DarthPresidente

-- Automatically destroys a mine AFTER it's storage has been removed
-- When a deposit is depleted it will automatically fire the manager and all workers
--   and close the worker slots.



OnMsg.ClassesPreprocess = function()
	Mining.Tick = function(self)
		local mine = self.parent
		if self.deposit and self.produced_amount ~= 0 then
			local depletion_rate = self:GetDepletionRate()
			depletion_rate = MulDivRound(depletion_rate, 100 - self.parent.city:GetSkillBonus("Magnate"), 100)
			if self.deposit:Take(MulDivRound(self.produced_amount, depletion_rate, 100)) == 0 then
				self.CursedByAntiBody = true
				DarthShutBuildingDown(mine)
			end
		end
		if self.CursedByAntiBody then
			if DarthGetStorage(mine) == 0 then
				AddOnScreenNotification("AutoDemolishNoDeposit", {Name = mine.props.Name}, GetLiveCamParams("deposit_depleted", mine))
				self.parent:StartDestruction()
				self.delete_deposit = self.deposit
				self:Unlink()	
			end
		end
	end
	Logging.Tick = function(self)
		local camp = self.parent
		if self.trees_to_cut > 0 and g_Grids.Trees:GetValue(camp:GetPos()) < self.MinTreesWork then
			self.CursedByAntiBody = true
			DarthShutBuildingDown(camp)
		end
		if self.CursedByAntiBody then
			if DarthGetStorage(camp) == 0 then
				local livecam = GetLiveCamParams("burning_building", camp)
				do
					local pos = camp:GetLogicPos()
					livecam.target_pos = function(target)
						if not IsValid(target) or not target:GetLogicPos() then
							return pos
						else
							return target:GetLogicPos()
						end
					end
					AddOnScreenNotification("AutoDemolishNoTrees", {Name = camp.props.Name}, livecam, camp.city)
					camp:StartDestruction()
				end
			--
			end
		end
	end
	DebugPrint("Mining & Logging SmartDestroy mod by DarthPresidente loaded...\n    Version:  	1.0\n    SourceFile: " .. debug.getinfo(1).source:match("@(.*)$") .. "\n\n")
end

DarthShutBuildingDown = function(bld)
	local wp = bld.workplace
	if wp then
		-- AutoFire the manager
		local manager = wp.manager
		if manager then 
			manager:SetManager(false) 
		end
		-- AutoFire the workers!
		for i = #wp.workers, 1, -1 do
			local worker = wp.workers[i]
			worker:GetFired("no bad feelings")
		end
		-- Close the positions!
		wp.closed_workplaces = wp:GetMaxWorkers()
		-- Set production to ZERO
		local production = bld.production
		for i = 1, #production do
			local prod = production[i].BaseOutputAmount
			if prod then
				bld.production[i].BaseOutputAmount = 0
			end
		end
		bld:SetBudgetLevel(1)
	end
end
DarthGetStorage = function(bld)
	local stored = 0
	if bld.storage then
		local resources = bld.storage.resources
		if resources then
			for k,v in pairs(resources) do
				stored = stored + resources[k].amount
			end
		end
	end
	return stored
end