require "MF_ISMoodle"
require "TimedActions/ISBaseTimedAction"

TABAS_DrySelf = ISBaseTimedAction:derive("TABAS_DrySelf")

function TABAS_DrySelf:isValid()
    return true
end

function TABAS_DrySelf:waitToStart()
    if self.character:isCurrentState(ClimbOverFenceState.instance()) then
        return true
    end
    return self.character:shouldBeTurning()
end

function TABAS_DrySelf:update()
end

function TABAS_DrySelf:start()
    local wetTime = self.character:getModData().bathingWetTimer or 0
    self.doDry = self.towel and (wetTime > 0 or self.character:getStats():get(CharacterStat.WETNESS) > 20)
    if self.doDry and not self.isBTO then
        self:setActionAnim("TABAS_DryYourSelf")
        self:setOverrideHandModels(nil, self.towel)
        self.sound = self.character:playSound("FirstAidCleanBurn")
    end
end

function TABAS_DrySelf:stopSound()
    if self.sound and self.character:getEmitter():isPlaying(self.sound) then
        self.character:stopOrTriggerSound(self.sound)
    end
end

function TABAS_DrySelf:stop()
    self:stopSound()
    ISBaseTimedAction.stop(self)
end

function TABAS_DrySelf:perform()
    self:stopSound()
    local bWet = 70
    if self.doDry then
        self.character:getModData().bathingWetTimer = 0
        if self.bathingWet ~= nil then
            self.bathingWet:setValue(0.5)
        end
        if self.isBTO then
            ISTimedActionQueue.add(BTO_WipeMySelf:new(self.character, self.towel, true, false, bWet))
        else
            self.character:getStats():set(CharacterStat.WETNESS, 0)
            self.towel:setCurrentUsesFloat(0)
        end
    elseif self.bathingWet == nil then
        self.character:getModData().bathingWetTimer = 0
        self.character:getStats():set(CharacterStat.WETNESS, bWet)
    end

    ISBaseTimedAction.perform(self)
end

function TABAS_DrySelf:complete()
    return true
end

function TABAS_DrySelf:adjustMaxTime(maxTime)
    return maxTime
end

function TABAS_DrySelf:getDuration()
	if self.character:isTimedActionInstant() then
		return 1
	end
    if self.towel and not self.isBTO then
        return 160
    end
    return 0
end

function TABAS_DrySelf:new(character, towel)
    local o = ISBaseTimedAction.new(self, character)
    setmetatable(o, self)
    self.__index = self
    o.towel = towel
    o.isBTO = BTO_Loaded and towel and towel:hasTag(BTO_Tag.Wipeable)
    o.character = character
    o.doDry = false
    o.maxTime = o:getDuration()
    if MF then -- Moodle Framework
        o.bathingWet = MF.getMoodle("Wet_Bathing", character:getPlayerNum())
    end
    -- o.stopOnWalk = false
    o.ignoreHandsWounds = true
    return o
end