local ProgressBar = class("ProgressBar")

function ProgressBar:runBar(params)
	local oldLv = params.oldLv
	local newLv = params.newLv
	local beginPer = params.beginPer
	local endPer = params.endPer
	local time = params.time or 0
	local endCallback = params.endCallback
	local perStep = params.perStep or 0.1

	if not params.ui then
		return
	end

	local function endSchedule(onlyClear)
		if self.scheduleId then
			params.ui:unscheduleGlobal(self.scheduleId)
			self.scheduleId = nil
		end
		if not onlyClear and endCallback then
			endCallback()
		end
	end

	local function runAddBar()
		beginPer = beginPer + perStep
		if beginPer > 1 then
			oldLv = oldLv + 1
			beginPer = beginPer - 1
		end
		if oldLv > newLv or (oldLv == newLv and beginPer >= endPer) then
			if params.callback then
				params.callback(newLv, endPer)
			end
			endSchedule()
			return
		else
			if params.callback then
				params.callback(oldLv, beginPer)
			end
		end
	end
	local function runSubBar()
		beginPer = beginPer - perStep
		if beginPer < 0 then
			oldLv = oldLv - 1
			beginPer = beginPer + 1
		end
		if oldLv < newLv or (oldLv == newLv and beginPer <= endPer) then
			if params.callback then
				params.callback(newLv, endPer)
			end
			endSchedule()
			return
		else
			if params.callback then
				params.callback(oldLv, beginPer)
			end
		end
	end
	local function runBar()
		if newLv > oldLv or (newLv == oldLv and endPer >= beginPer) then
			runAddBar()
		elseif newLv < oldLv or (newLv == oldLv and endPer < beginPer) then
			runSubBar()
		else
			self:endSchedule()
		end
	end

	endSchedule(true)

	self.scheduleId = params.ui:scheduleGlobal(function ()
		runBar()
	end, time)
	runBar()
end

return ProgressBar