require("ISUI/ISPanelJoypad")

-- ** UI for Tub Fluid Container referenced by ISFluidInfoUI. ** 

TABAS_TubFluidContainerInfoUI = ISPanelJoypad:derive("TABAS_TubFluidContainerInfoUI")

TABAS_TubFluidContainerInfoUI.players = {}

local TABAS_Utils = require("TABAS_Utils")
local TABAS_Panel = require("UI/TABAS_PanelUtils")

local CONST = require("UI/TABAS_PanelConst")
local FONT_HGT_SMALL = CONST.SCALE.HGT_SMALL
local FONT_HGT_MEDIUM = CONST.SCALE.HGT_MEDIUM
local MAX_PANEL_DIST = 5
local BETWEEN_SPACING = CONST.SCALE.BETWEEN_SPACING
local BORDER_SPACING = CONST.SCALE.BORDER_SPACING

function TABAS_TubFluidContainerInfoUI.OpenPanel(playerObj, tfc_Base)
    local playerNum = playerObj:getPlayerNum()

    local x = getMouseX() + 10
    local y = getMouseY() + 10
    local adjustPos = true
    local this = TABAS_TubFluidContainerInfoUI
    if this.players[playerNum] then
        if this.players[playerNum].instance then
            this.players[playerNum].instance:close()
            if this.players[playerNum].x and this.players[playerNum].y then
                x = this.players[playerNum].x
                y = this.players[playerNum].y
                adjustPos = false
            end
        end
    else
        this.players[playerNum] = {}
    end

    local ui = this:new(x, y, 800, 500, playerObj, tfc_Base)
    ui:initialise()
    ui:instantiate()
    ui:setVisible(true)
    ui:addToUIManager()

    this.players[playerNum].instance = ui

    --first time open panel and isoobject then middle of screen.
    if getJoypadData(playerNum) or adjustPos then
        ui:centerOnScreen(playerNum)
        this.players[playerNum].x = ui.x
        this.players[playerNum].y = ui.y
    end

    if getJoypadData(playerNum) then
        setJoypadFocus(playerNum, ui)
    end
end

function TABAS_TubFluidContainerInfoUI:initialise()
    ISPanelJoypad.initialise(self)


end

function TABAS_TubFluidContainerInfoUI:createChildren()
    ISPanelJoypad.createChildren(self)

    local x = BORDER_SPACING
    local y = self.titleHeigh + BORDER_SPACING * 1.5
    local addPanel = function(class, targetPanel, anchor, setW, setH)
        local panel = class:new(x, y, self.playerObj, self.tfc_Base)
        panel:initialise()
        panel:instantiate()
        self:addChild(panel)
        if targetPanel and anchor then
            self:layoutPanel(panel, targetPanel, anchor, setW, setH)
        end
        return panel
    end
    -- bathtub status panel.
    self.tubStatusPanel = addPanel(TABAS_TubStatusPanel)
    -- tub water status panel.
    self.tubWaterStatusPanel = addPanel(TABAS_TubWaterStatusPanel, self.tubStatusPanel, "BOTTOM", self.tubStatusPanel:getWidth())
    -- temperature panel
    self.temperaturePanel = addPanel(TABAS_TubTemperaturePanel, self.tubStatusPanel, "RIGHT")
    -- bath salt panel
    self.bathSaltPanel = addPanel(TABAS_BathSaltDropBoxPanel, self.temperaturePanel, "RIGHT", nil, self.temperaturePanel:getHeight())

    -- tub fluid container panel
    local panelWidth = self.temperaturePanel:getWidth()+self.bathSaltPanel:getWidth()+BETWEEN_SPACING
    self.tfcPanel = TABAS_TubFluidContainerPanel:new(self.temperaturePanel:getX(), self.temperaturePanel:getBottom()+BETWEEN_SPACING, panelWidth, panelWidth * 0.55, self.playerObj, self.tfc_Base)
    self.tfcPanel:initialise()
    self.tfcPanel:instantiate()
    self:addChild(self.tfcPanel)

    -- take bath button
    local btnScale = FONT_HGT_SMALL * 1.25
    panelWidth = self.tfcPanel:getWidth() - btnScale - BETWEEN_SPACING
    self.btnTakeBath = TABAS_Panel.addButton(x, y, panelWidth, FONT_HGT_MEDIUM, nil, getText("IGUI_TABAS_TakeBath"), nil, self, self.onClick, true)
    self.btnTakeBath.internal = "TAKEBATH"
    self.btnTakeBath:setFont(UIFont.Medium)
    self:insertNewLineOfButtons(self.btnTakeBath)
    self:layoutPanel(self.btnTakeBath, self.tfcPanel, "BOTTOM")

    -- bath time entry panel.
    self.entryPanel = addPanel(TABAS_BathTimeEntryPanel, self.tfcPanel, "LEFT")
    self.entryPanel:setY(self.btnTakeBath:getBottom() - self.entryPanel:getHeight())


    -- config button
    self.btnConfig = TABAS_Panel.addButton(x, y, btnScale, btnScale, self.tex_configIcon, nil, nil, self, self.onClick, true)
    self.btnConfig.internal = "CONFIG"
    self:layoutPanel(self.btnConfig, self.btnTakeBath, "RIGHT")

    self:setWidth(self.btnConfig:getRight() + BORDER_SPACING)
    self:setHeight(self.btnTakeBath:getBottom() + BORDER_SPACING*2)

    x = BORDER_SPACING/2
    y = FONT_HGT_SMALL / 6
    btnScale = FONT_HGT_SMALL
    -- close button
    self.btnClose = TABAS_Panel.addButton(x, y, btnScale, btnScale, self.tex_closeButton, nil, nil, self, self.onClick, false)
    self.btnClose.internal = "CLOSE"
    if getJoypadData(self.playerNum) then
        self.btnClose.title = getText("IGUI_DebugMenu_Close")
        self.btnClose.image = nil
    end
    -- pin button
    x = self:getWidth() - btnScale - BORDER_SPACING/2
    self.btnPin = TABAS_Panel.addButton(x, y, btnScale, btnScale, self.tex_pinButton, nil, nil, self, self.onClick, false)
    self.btnPin.internal = "PIN"
    self.pinned = false

end

function TABAS_TubFluidContainerInfoUI:layoutPanel(panel, targetPanel, anchor, width, height)
    if anchor == "LEFT" then
        panel:setX(targetPanel:getX() - panel:getWidth() - BETWEEN_SPACING)
        panel:setY(targetPanel:getY())
    elseif anchor == "RIGHT" then
        panel:setX(targetPanel:getRight() + BETWEEN_SPACING)
        panel:setY(targetPanel:getY())
    elseif anchor == "BOTTOM" then
        panel:setX(targetPanel:getX())
        panel:setY(targetPanel:getBottom() + BETWEEN_SPACING)
    elseif anchor == "TOP" then
        panel:setX(targetPanel:getX())
        panel:setY(targetPanel:getY() - panel:getHeight() - BETWEEN_SPACING)
    end
    if width then
        panel:setWidth(width)
    end
    if height then
        panel:setHeight(height)
    end
end

function TABAS_TubFluidContainerInfoUI:prerender()
    ISPanelJoypad.prerender(self)
    local col = CONST.COLOR.borderColor
    -- title text
    self:drawTextureScaled(self.tex_titleBG, 0, 0, self:getWidth() - 2, self.titleHeigh - 1, 1, 1, 1, 1);
    self:drawRectBorder(0, 0, self:getWidth(), self.titleHeigh, col.a, col.r, col.g, col.b)
    self:drawTextCentre(self.title, self:getWidth() / 2, 1, 1, 1, 1, 1, UIFont.Medium)
    if getJoypadData(self.playerNum) then
        local tex = Joypad.Texture.RBumper
        local texWidth = tex:getWidth()
        local texHeight = tex:getHeight()
        local x = self.entryPanel:getRight() - texWidth - BORDER_SPACING
        local y = self.entryPanel.y - texHeight
        self:drawTextureScaled(tex, x, y, texWidth, texHeight, 1, 1, 1, 1)
        tex = getTexture("media/ui/Entity/BTN_Swap_Icon_48x48.png")
        self:drawTextureScaled(tex, x - texWidth - BORDER_SPACING, y, texWidth, texHeight, 1, 1, 1, 1)
        tex = Joypad.Texture.LBumper
        self:drawTextureScaled(tex, x - texWidth*2 - BORDER_SPACING*2, y, texWidth, texHeight, 1, 1, 1, 1)
    end
end

function TABAS_TubFluidContainerInfoUI:render()
    self:switchJoypadFocus(self.joypadIndex, self.joypadIndexY)
end

function TABAS_TubFluidContainerInfoUI:update()
    self.tfcPanel:updateButtons()

    local col = self.pinned and CONST.COLOR.variableColor or {r=0.5, g=0.5, b=0.5, a=1}
    self.btnPin:setTextureRGBA(col.r, col.g, col.b, col.a)
    self.btnTakeBath:setEnable(self.tfc_Base:getRatio() > self.tfc_Base.filledConst.HalfLow)

    --range check for isoPanels.
    if not self.pinned then
        if self.tfc_Base and self.tfc_Base.square and self.playerObj then
            local square = self.tfc_Base.square
            local dist = MAX_PANEL_DIST
            if self.playerObj:getX() < square:getX()-dist or self.playerObj:getX() > square:getX()+dist or self.playerObj:getY() < square:getY()-dist or self.playerObj:getY() > square:getY()+dist then
                self:close()
                return
            end
        else
            self:close()
            return
        end
    end
end

function TABAS_TubFluidContainerInfoUI:close()
    if self.configPanel and self.configPanel.instance ~= nil then
        self.configPanel:close()
    end
    if self.playerObj then
        if TABAS_TubFluidContainerInfoUI.players[self.playerNum] then
            TABAS_TubFluidContainerInfoUI.players[self.playerNum].x = self:getX()
            TABAS_TubFluidContainerInfoUI.players[self.playerNum].y = self:getY()
        end
        if JoypadState.players[self.playerNum+1] then
            setJoypadFocus(self.playerNum, nil)
        end
    end
    self:setVisible(false)
    self:removeFromUIManager()
end

function TABAS_TubFluidContainerInfoUI:clickedDropBox(x, y)
    self.bathSaltPanel:clickedDropBox(x, y)
end

function TABAS_TubFluidContainerInfoUI:onClick(_btn)
    self.bathSaltPanel:onClick(_btn)
    self.temperaturePanel:onClick(_btn)
    self.entryPanel:onClick(_btn)

    if _btn.internal == "CLOSE" then
        return self:close()
    elseif _btn.internal == "PIN" then
        self.pinned = not self.pinned
        return
    elseif _btn.internal == "CONFIG" then
        if self.configPanel and self.configPanel.instance ~= nil then
            self.configPanel:close()
            self.configPanel = nil
        else
            self.configPanel = TABAS_ConfigPanel.openPanel(0, 0, self.playerObj)
        end
        return
    end
    local actionQueue = ISTimedActionQueue.getTimedActionQueue(self.playerObj)
    local doAction = actionQueue.queue[1] ~= nil
    if not doAction then
       self.tfcPanel:onClick(_btn)
        if _btn.internal == "TAKEBATH" then
            local player = self.playerObj:getPlayerNum()
            local bathTime = self.entryPanel:getEntryTime()
            local towel = self.entryPanel:getStoredItem()
            local asIsWearing = not TABAS_Utils.ModOptionsValue("AutoClothesChange")
            local TakeBathContext = require("TABAS_ContextMenuBathtub")
            TakeBathContext.onTakeBath(player, self.tfc_Base, towel, asIsWearing, bathTime)
            self:close()
        end
    end
end

function TABAS_TubFluidContainerInfoUI:onGainJoypadFocus(joypadData)
    ISPanelJoypad.onGainJoypadFocus(self, joypadData)
    self:setISButtonForB(self.btnClose)

    self.joypadButtons = {}
    self.joypadButtonsY = {}
    local tempePanel = self.temperaturePanel
    local bathSaltPanel = self.bathSaltPanel
    self:insertNewLineOfButtons(tempePanel.btnReheat, tempePanel.btnSetTempe, bathSaltPanel.btnAdd, bathSaltPanel.itemDropBoxJoypad)
    self:insertNewLineOfButtons(self.tfcPanel.btnFill)
    self:insertNewLineOfButtons(self.tfcPanel.btnStop)
    self:insertNewLineOfButtons(self.tfcPanel.btnEmpty)
    self:insertNewLineOfButtons(self.btnTakeBath, self.btnConfig)
    self.joypadIndex = self.prevJoypadIndex or 1
    self.joypadIndexY = self.prevJoypadIndexY or #self.joypadButtonsY

    self:restoreJoypadFocus(joypadData)
    self:switchJoypadFocus(self.joypadIndex, self.joypadIndexY)
end

function TABAS_TubFluidContainerInfoUI:switchJoypadFocus(joypadIndex, joypadIndexY)
    if joypadIndex > 0 then
        local indexY = self.joypadButtonsY[joypadIndexY]
        if indexY and indexY[joypadIndex] then
            local parent = indexY[joypadIndex].parent
            if parent then
                parent:setJoypadFocused(true)
                parent:renderJoypadFocus()
            end
            if self.btnConfig.joypadFocused then
                self.btnConfig:renderJoypadFocus()
            end
        end
    end
end

function TABAS_TubFluidContainerInfoUI:onLoseJoypadFocus(joypadData)
    ISPanelJoypad.onLoseJoypadFocus(self, joypadData)
    self.prevJoypadIndex = self.joypadIndex
    self.prevJoypadIndexY = self.joypadIndexY
    self:clearJoypadFocus(joypadData)
end

function TABAS_TubFluidContainerInfoUI:onJoypadDown(button, joypadData)
    if button == Joypad.BButton then
        self:close()
        return
    end
    if button == Joypad.LBumper then
        joypadData.focus:setJoypadFocused(false, joypadData)
        setJoypadFocus(self.playerNum, self.entryPanel)
        return
    end
    ISPanelJoypad.onJoypadDown(self, button, joypadData)
end

function TABAS_TubFluidContainerInfoUI:new(x, y, width, height, playerObj, tfc_Base)
    local o = ISPanelJoypad.new(self, x, y, width, height)
    o.title = getText("IGUI_TABAS_BathtubInfo_Title")
    o.titleHeigh = FONT_HGT_MEDIUM
    o.backgroundColor = CONST.COLOR.backgroundColorDark
    o.tex_configIcon = getTexture("media/ui/Icons/tabas_configIcon.png")

    o.tex_infoIcon = getTexture("media/ui/Panel_info_button.png")
    o.tex_pinButton = getTexture("media/ui/inventoryPanes/Button_Pin.png")
    o.tex_closeButton = getTexture("media/ui/inventoryPanes/Button_Close.png")
    o.tex_titleBG = getTexture("media/ui/Panel_TitleBar.png")
    o.tex_statusBG = getTexture("media/ui/Panel_StatusBar.png")
    o.tex_btnBG = getTexture("media/ui/Backgrounds/tabas_buttonBG.png")

    o.moveWithMouse = true

	o.pinned = false
    o.playerObj = playerObj
    o.playerNum = playerObj:getPlayerNum()
    o.tfc_Base = tfc_Base
    return o
end