--================================ Feed NPC UI ================================--
--CỬA SỔ DANH SÁCH ĐỒ ĂN TRONG TÚI ĐỒ PLAYER
--CALL FUNCTION: VLF.QuestUI.FoodsInINVWindow(player, qStep, zNPC, foodList)
--=============================================================================--

require "ISUI/ISPanelJoypad"
require "ISUI/ISUIElement"
require "ISUI/ISCollapsableWindow"
require "ISUI/ISScrollingListBox"

VL_Quest_Feed_NPC = ISCollapsableWindow:derive("VL_Quest_Feed_NPC")

VLF.QuestUI = VLF.QuestUI or {}

local GetPlayerGlobalModDataQ1 = VLGMD.GetPlayerGlobalModDataQ1
local GetFoodInContainer = VLIT.GetFoodInContainer
local SetPlayerGMD_Q1 = VLGMD.SetPlayerGMD_Q1
local RemoveItemFromContainer = VLIT.RemoveItemFromContainer
local Caldistance = VLF.Caldistance
local GetHungerFromFood = VLIT.GetHungerFromFood
local AddReputationPoint = VLGMD.AddReputationPoint

local fontHeightSmall = getTextManager():getFontHeight(UIFont.Small)    --26
local fontHeightMedium = getTextManager():getFontHeight(UIFont.Medium)
local fontHeightLarge = getTextManager():getFontHeight(UIFont.Large)

function VL_Quest_Feed_NPC:createChildren()
    ISCollapsableWindow.createChildren(self)
end

function VL_Quest_Feed_NPC:prerender()
    ISCollapsableWindow.prerender(self)
    self:drawTextCentre(getText("IGUI_VLQ_TakeCare_FeedUI_Title"), self.width / 2, 0, 1, 1, 1, 1, UIFont.Small)
    self:drawTextCentre(getText("IGUI_VLQ_TakeCare_FeedUI_TipGuideFeedNPC"), self.width / 2, fontHeightSmall, 1, 1, 1, 0.9, UIFont.Small)
end

function VL_Quest_Feed_NPC:render()
    ISCollapsableWindow.render(self)
end

function VL_Quest_Feed_NPC:close()
    self:setVisible(false)
    self:removeFromUIManager()
    
    --reset window
    VLF.var.showFoodsInINVWindow = nil
end

--Close khi ấn ESC
function VL_Quest_Feed_NPC:onKeyPress(key)
    if key == Keyboard.KEY_ESCAPE then
        self:close()
    end
end

function VL_Quest_Feed_NPC:new(player, width, height, qStep, zNPC, foodList)
    local playerNum = player:getPlayerNum()
    local x = (getPlayerScreenWidth(playerNum) / 10)
    local y = (getPlayerScreenHeight(playerNum) / 10)

    local o = ISCollapsableWindow.new(self, x, y, width, height)
    o.player = player
    o.qStep = qStep
    o.foodList = foodList
    o.zNPC = zNPC
    o.playerNum = playerNum
    o.moveWithMouse = true
    o.anchorLeft = true
    o.anchorRight = true
    o.anchorTop = true
    o.anchorBottom = true
    o.resizable = true
    o:setWantKeyEvents(true)
    return o
end

function VL_Quest_Feed_NPC:initialise()
    ISCollapsableWindow.initialise(self)

    --Khởi tạo khu vực trong UI có thể scroll chuột
    local y = fontHeightSmall * 2

    self.questList = ISScrollingListBox:new(10, y, self.width - 20, self.height - y - 20)
    self.questList:initialise()
    self.questList:instantiate()
    self.questList.itemheight = fontHeightSmall * 10 --(26 * 10 = 260)
    self.questList.selected = 0
    self.questList.joypadParent = self
    self.questList.font = UIFont.NewSmall
    self.questList.doDrawItem = self.drawQuestItem
    self.questList.drawBorder = true
    self:addChild(self.questList)
    
    local qStep = self.qStep
    local foodList = self.foodList
    local player = self.player
    local zNPC = self.zNPC
    
    --Click chuột 2 lần để cho NPC ăn
    --onMouseDoubleClick
    function self.questList:onMouseDoubleClick(x, y)
        -- Gọi lại hành vi gốc để cập nhật self.selected
        ISScrollingListBox.onMouseDoubleClick(self, x, y)
        if self.selected > 0 then
            local item = self.items[self.selected]
            if item.item and item.item.id then
                local foodIndex = item.item.id
                --kiểm tra có ở gần NPC
                if Caldistance(player, zNPC) < 2.5 then
                    local inv = player:getInventory()
                    
                    --kiểm tra còn item đó trong container không. true == Đệ Quy
                    if inv:contains(foodList[foodIndex], true) then
                        
                        --kiểm tra NPC có đói để có thể ăn không
                        local playerGMD_Quest_Q1 = GetPlayerGlobalModDataQ1(player, qStep)
                        if playerGMD_Quest_Q1[qStep].npcHunger > 15 then
                            local food = foodList[foodIndex]
                            local removed = RemoveItemFromContainer(inv, food, nil, 1)
                            if removed == true then
                                VLF.var.showFoodsInINVWindow:close()
                                zNPC:getEmitter():playSound("Eating")
                                
                                --Giảm hunger cho NPC			
                                local hungerChange = GetHungerFromFood(food)

                                local hunger = playerGMD_Quest_Q1[qStep].npcHunger + hungerChange
                                if hunger < 0 then hunger = 0 end
                                SetPlayerGMD_Q1(player, qStep, "npcHunger", hunger)
                                
                                --Đồ ăn có độc thì tăng cấp độ nhiễm độc
                                if food:isPoison() or food:getPoisonPower() > 0 then
                                    local poisonedLvl = playerGMD_Quest_Q1[qStep].npcPoisonedLvl + 1
                                    if poisonedLvl > 5 then poisonedLvl = 5 end     --giới hạn max cấp độ nhiễm độc là 5
                                    SetPlayerGMD_Q1(player, qStep, "npcPoisonedLvl", poisonedLvl)
                                    print("Client---Given NPC Poisoned Food= ", playerGMD_Quest_Q1[qStep].npcPoisoned, playerGMD_Quest_Q1[qStep].npcPoisonedLvl)
                                end
                                
                                --Nếu là Base.LemonGrass thì giảm 5 nhiễm độc
                                 if food:getFullType() == "Base.LemonGrass" then
                                    local poisoned = playerGMD_Quest_Q1[qStep].npcPoisoned - 5
                                    if poisoned < 0 then poisoned = 0 end
                                    if poisoned ~= playerGMD_Quest_Q1[qStep].npcPoisoned then
                                        SetPlayerGMD_Q1(player, qStep, "npcPoisoned", poisoned)
                                    end
                                end
                                
                                AddReputationPoint(player, 1)
                            end
                        else
                            HaloTextHelper.addBadText(player, getText("IGUI_VLQ_Notification_NPCNotHungry"))
                        end
                    else
                         HaloTextHelper.addBadText(player, getText("IGUI_VLQ_Notification_ItemNotExist"))
                    end
                else
                    HaloTextHelper.addBadText(player, getText("IGUI_VLQ_Notification_Distance"))
                end
            end
        end
    end
    ------------------------------------------------------------------

    --hiển thị hết tất cả thức ăn có hunger trong túi
    --local foodList = {}
    --local inv = self.player:getInventory()
   -- GetFoodInContainer(inv, foodList)
    if #foodList > 0 then
        for i, food in ipairs(foodList) do
            if food and not food:isRotten() and not food:isbDangerousUncooked() then
                --local hungerChange = math.floor(food:getHungChange() * 100 + 0.5) or 0  --getHungChange có giá trị -0.xxx...
                local hungerChange = GetHungerFromFood(food)
                self.questList:addItem("Food_" .. i, {id = i, qStep = qStep, foodName = food:getName(), hungerChange = hungerChange})
            end
        end
    end
end
 
--DRAW TẤT CẢ CÁC ITEM Ở addItem
function VL_Quest_Feed_NPC:drawQuestItem(y, item, alt)
    --local a = 0.8
    local r, g, b, a = 0.98, 0.98, 0.98, 1
    local xOffset = 10
    local yOffset = y
    local iData = item.item
    local itemHeight = self.itemheight

    --Vẽ đường viền mỗi ô
    self:drawRectBorder(0, y, self:getWidth(), fontHeightSmall, a, self.borderColor.r, self.borderColor.g, self.borderColor.b)
    if self.selected == item.index then
        self:drawRect(0, y, self:getWidth(), fontHeightSmall, 1, 0.17647, 0.26667, 0.26667)
    end
    
    local text = iData.id .. ".   " .. iData.foodName .. ",   hunger " .. tostring(iData.hungerChange)
    
    self:drawText(text, xOffset, yOffset, 1, 1, 1, 1, UIFont.Small)

    return y + fontHeightSmall
end

--CALL
function VLF.QuestUI.FoodsInINVWindow(player, qStep, zNPC, foodList)
    if not VLF.var.showFoodsInINVWindow then
        VLF.var.showFoodsInINVWindow = VL_Quest_Feed_NPC:new(player, 700, 500, qStep, zNPC, foodList)
        VLF.var.showFoodsInINVWindow:initialise()
        VLF.var.showFoodsInINVWindow:addToUIManager()
    else
        VLF.var.showFoodsInINVWindow:close()
    end
end





