require "ISUI/ISPanel"
require('ISUI/ISScrollingListBox')
local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.NewSmall)
local FONT_HGT_MEDIUM = getTextManager():getFontHeight(UIFont.NewMedium)
local FONT_HGT_LARGE = getTextManager():getFontHeight(UIFont.NewLarge)
PlayerGetPointseUI = ISPanel:derive("PlayerGetPointseUI");
local this = PlayerGetPointseUI

local btnPlayerGetPointseUI = getText("IGUI_ASM_Buy")
local btnClose = getText("IGUI_CraftUI_Close")
local btnCompleteWid = getTextManager():MeasureStringX(UIFont.NewSmall, btnPlayerGetPointseUI) + 10
local btnCompleteHgt = getTextManager():MeasureStringY(UIFont.NewSmall, btnPlayerGetPointseUI) + 10
local btnCloseWid = getTextManager():MeasureStringX(UIFont.NewSmall, btnClose) + 10
local btnCloseHgt = getTextManager():MeasureStringY(UIFont.NewSmall, btnClose) + 10
function PlayerGetPointseUI:initialise()
    ISPanel.initialise(self);
    self:create();
end

function PlayerGetPointseUI:prerender()
    ISPanel.prerender(self);
    self.drawText(self, getText("IGUI_ASM_YourPoint"),
        self.width - (getTextManager():MeasureStringX(UIFont.NewSmall, getText("IGUI_ASM_YourPoint"))) - 10, 10, 1, 1,
        1, 1, UIFont.NewSmall);
    local ModData = self.character:getModData()
    if ModData.ATPoint then
        self.drawText(self, tostring(ModData.ATPoint),
            self.width - (getTextManager():MeasureStringX(UIFont.NewSmall, tostring(ModData.ATPoint))) - 10,
            10 + FONT_HGT_SMALL, 1, 1, 1, 1, UIFont.NewSmall);
    else
        self.drawText(self, "0", self.width - (getTextManager():MeasureStringX(UIFont.NewSmall, "0")) - 10,
            10 + FONT_HGT_SMALL, 1, 1, 1, 1, UIFont.NewSmall);
    end
end

function PlayerGetPointseUI:destroy()
    UIManager.setShowPausedMessage(true)
    self:setVisible(false)
    self:removeFromUIManager()
end

local Ammo = {{
    Type = "AutoTurret.30mmAmmo",
    Money = 30
}, {
    Type = "AutoTurret.20mmAmmo",
    Money = 20
}, {
    Type = "AutoTurret.50mmAmmo",
    Money = 50
}, {
    Type = "AutoTurret.60mmAmmo",
    Money = 60
}, {
    Type = "AutoTurret.88mmAmmo",
    Money = 88
}}

function PlayerGetPointseUI:update()
    ISPanel.update(self)
end

local Tick = 0
local RenderTick = 5
function PlayerGetPointseUI:render()

end

function PlayerGetPointseUI:create()

    self.Buy = ISButton:new(self.width - btnCompleteWid - 5, self.height - btnCompleteHgt - 5, btnCompleteWid,
        btnCompleteHgt, btnPlayerGetPointseUI, self, this.onOptionMouseDown);
    self.Buy.internal = "Buy";
    self.Buy:initialise();
    self.Buy:instantiate();
    self.Buy.borderColor = {
        r = 1,
        g = 1,
        b = 1,
        a = 0.1
    }
    self:addChild(self.Buy);

    self.close = ISButton:new(self.width - btnCompleteWid - btnCompleteWid - btnCloseWid,
        self.height - btnCompleteHgt - 5, btnCompleteWid, btnCompleteHgt, btnClose, self, this.onOptionMouseDown);
    self.close.internal = "Close";
    self.close:initialise();
    self.close:instantiate();

    self.close.borderColor = {
        r = 1,
        g = 1,
        b = 1,
        a = 0.1
    }
    self:addChild(self.close);

    self.scrollingListItem = ISScrollingListBox:new(10, 20, 200, self.height - 25 - btnCompleteHgt)
    self.scrollingListItem.anchorRight = true
    self.scrollingListItem.anchorBottom = true
    self.scrollingListItem.itemheight = FONT_HGT_SMALL * 2
    self.scrollingListItem:initialise();
    self.scrollingListItem:instantiate();
    self.scrollingListItem.selected = 0
    self.scrollingListItem.joypadParent = self;
    self.scrollingListItem.font = UIFont.NewMedium;
    self.scrollingListItem.doDrawItem = self.drawItem
    self.scrollingListItem.drawBorder = true;
    self:addChild(self.scrollingListItem);
    self:initList()

    self.textEntry = ISTextEntryBox:new("1", self.width - btnCompleteWid, self.height - 3 * btnCompleteHgt - 5,
        btnCompleteHgt, 10, 10, 10);
    self.textEntry.font = UIFont.Medium
    self.textEntry:initialise();
    self.textEntry:instantiate();
    self.textEntry.backgroundColor = {
        r = 0,
        g = 0,
        b = 0,
        a = 0.5
    };
    self.textEntry.borderColor = {
        r = 1,
        g = 1,
        b = 1,
        a = 0.0
    };
    self.textEntry:setHasFrame(true)
    self.textEntry:setAnchorTop(false);
    self.textEntry:setAnchorBottom(true);
    self.textEntry:setAnchorRight(true);
    self:addChild(self.textEntry)
end

local function Copy_Table(tab)
    local ret = {}
    for k, v in pairs(tab) do
        if type(v) == "table" then
            ret[k] = Copy_Table(v)
        else
            ret[k] = v
        end
    end
    return ret
end

function PlayerGetPointseUI:initList()
    local CategoryList = Ammo
    local NewTable = Copy_Table(CategoryList)
    for k, v in pairs(NewTable) do
        v.Money = v.Money * SandboxVars.AutoTurret.AmmoPrice
        self.scrollingListItem:addItem(k, v)
    end
end

local function DeletePlayerHasMoney(Item, Num, playerObj)
    local ModData = playerObj:getModData()
    if ModData.ATPoint then
        if ModData.ATPoint >= Item.Money * Num then
            ModData.ATPoint = ModData.ATPoint - Item.Money * Num
            return true
        else
            playerObj:Say(getText("IGUI_ASM_NoEnoughPoint"))
            return false
        end
    else
        playerObj:Say(getText("IGUI_ASM_NoEnoughPoint"))
        return false
    end
end

function PlayerGetPointseUI:onOptionMouseDown(button, x, y)
    if button.internal == "Buy" then
        if self.scrollingListItem.selected then
            if self.scrollingListItem.items then
                local Item = self.scrollingListItem.items[self.scrollingListItem.selected]
                if Item then
                    Item = Item.item
                    local Num = tonumber(self.textEntry:getText())
                    if not Num then
                        Num = 1
                        self.character:Say(getText("IGUI_ASM_WrongNumber"))
                    end
                    if DeletePlayerHasMoney(Item, Num, self.character) then
                        self.character:getInventory():AddItems(Item.Type, Num)
                        local itemName = instanceItem(Item.Type):getDisplayName()
                        self.character:Say(getText("IGUI_ASM_BuyItem") .. itemName .. "*" .. Num)
                    end
                else
                    self.character:Say(getText("IGUI_ASM_NoItemSelected"))
                end
            end
        end
    end
    if button.internal == "Close" then
        self:destroy()
    end
end

function PlayerGetPointseUI:drawItem(_y, _item, _alt)
    if _y + self:getYScroll() + self.itemheight < 0 or _y + self:getYScroll() >= self.height then
        return _y + self.itemheight
    end
    local unit = _item.item
    if self.selected == _item.index then
        self:drawRect(0, (_y), self:getWidth(), self.itemheight, 0.3, 1, 1, 0)
    end
    local Item = instanceItem(unit.Type)
    local ItemName = "5 * " .. Item:getDisplayName()
    local ItemNameW = getTextManager():MeasureStringX(UIFont.NewSmall, ItemName)
    local ItemTexture = Item:getTexture()
    self:drawRectBorder(0, (_y), self:getWidth(), self.itemheight, 0.5, 1, 1, 1)
    self:drawText(ItemName, 50, _y + FONT_HGT_SMALL, 0, 1, 0, 1, UIFont.NewSmall)
    self:drawTextureScaledAspect(ItemTexture, 0, _y + 5, 32, 32, 2, 2, 2, 2)
    local PointsNeed = unit.Money
    if PointsNeed then
        local PointsNeedW = getTextManager():MeasureStringX(UIFont.NewSmall, tostring(PointsNeed))
        self:drawText(tostring(PointsNeed), 50, _y, 0, 1, 0, 1, UIFont.NewSmall)
    end

    return _y + self.itemheight
end

function PlayerGetPointseUI:new(x, y, width, height, player)
    local o = {};
    o = ISPanel:new(x, y, width, height);
    setmetatable(o, self);
    o.character = player;
    self.__index = self;
    this.instance = o
    o.RankLevel = 1
    o.Category = nil
    o.LastCategory = nil
    o.ItemCategory = nil
    o.LastItemCategory = nil
    o.moveWithMouse = true;
    o.Item = nil
    o.anchorRight = true
    o.anchorBottom = true
    o.anchorTop = true
    o.anchorLeft = true
    return o;
end

function OpenPlayerGetPointseUIWindow(width, height)
    Creat100Mission()
    local maxY = getCore():getScreenHeight()
    local maxX = getCore():getScreenWidth()
    local x = (maxX - 400) / 2 + width
    local y = (maxY - 600) / 2
    local PlayerGetPointseUI = PlayerGetPointseUI:new(x, y, width, width, getSpecificPlayer(0));
    PlayerGetPointseUI:initialise();
    PlayerGetPointseUI:addToUIManager();
end

local function CheckPlayer(square)
    local playerObj = getPlayer()
    local x = playerObj:getX()
    local y = playerObj:getY()
    local sqareX = square:getX()
    local sqareY = square:getY()
    local Distance = math.sqrt((x - sqareX) ^ 2 + (y - sqareY) ^ 2)
    if Distance > 2.5 then
        local adjacent = AdjacentFreeTileFinder.Find(square, playerObj)
        if adjacent ~= nil then
            ISTimedActionQueue.add(ISWalkToTimedAction:new(playerObj, adjacent))
        end
    else
        if PlayerGetPointseUI.instance then
            PlayerGetPointseUI.instance:destroy()
        end
        local maxY = getCore():getScreenHeight()
        local maxX = getCore():getScreenWidth()
        local x = (maxX - 350) / 2
        local y = (maxY - 450) / 2
        local PlayerGetPointseUI = PlayerGetPointseUI:new(x, y, 350, 450, getSpecificPlayer(0));
        PlayerGetPointseUI:initialise();
        PlayerGetPointseUI:addToUIManager();
    end
end

local function OpenShopWindonw(_player, context, worldobjects)
    local objFound = false
    local object = nil;
    local objType = nil;
    for _, wObj in ipairs(worldobjects) do
        local square = wObj:getSquare()
        if square then
            for i = 1, square:getObjects():size() do
                object = square:getObjects():get(i - 1)
                if object:getContainer() then
                    objType = object:getContainer():getType():gsub("vending", "");
                    if (objType == "pop" or objType == "snack") then
                        context:addOption(getText("ContextMenu_OpenPlayerGetPoint"), square, CheckPlayer);
                        return
                    end
                end
            end
        end
    end
end

Events.OnPreFillWorldObjectContextMenu.Add(OpenShopWindonw);
local function UseAmmoBuilder(_player, _context, _items) -- 设置你的物品的右键菜单来打开窗口
    local container = nil
    local resItems = {}
    for i, v in ipairs(_items) do
        if not instanceof(v, "InventoryItem") then
            for _, it in ipairs(v.items) do
                resItems[it] = true
            end
            container = v.items[1]:getContainer()
        else
            resItems[v] = true
            container = v:getContainer()
        end
    end
    local square = getPlayer():getCurrentSquare()
    for v, _ in pairs(resItems) do
        if v:getType() == "EtherAmmoBuilder" then
            _context:addOption(getText("ContextMenu_OpenPlayerGetPoint"), square, CheckPlayer);
            return
        end
    end
end

Events.OnFillInventoryObjectContextMenu.Add(UseAmmoBuilder)
