    require "ISUI/ISPanel"
require "ISUI/ISButton"
require "ISUI/ISInventoryPane"
require "ISUI/ISResizeWidget"
require "ISUI/ISMouseDrag"

require "defines"

MapSelecter = ISPanelJoypad:derive("MapSelecter");
MapSelecter.imageSize = 128
MapSelecter.padXY = 16

function MapSelecter:initialise()
	ISPanel.initialise(self);
end

--************************************************************************--
--** ISPanel:instantiate
--**
--************************************************************************--
function MapSelecter:instantiate()

	--self:initialise();
	self.javaObject = UIElement.new(self);
	self.javaObject:setX(self.x);
	self.javaObject:setY(self.y);
	self.javaObject:setHeight(self.height);
	self.javaObject:setWidth(self.width);
	self.javaObject:setAnchorLeft(self.anchorLeft);
	self.javaObject:setAnchorRight(self.anchorRight);
	self.javaObject:setAnchorTop(self.anchorTop);
	self.javaObject:setAnchorBottom(self.anchorBottom);


end

function MapSelecter:prerender()

	ISPanel.prerender(self);
	self:drawTextCentre(getText("UI_mapselecter_title"), self.width / 2, 10, 1, 1, 1, 1, UIFont.Cred2);
	self:disableBtn();

end

function MapSelecter:drawMap(y, item, alt)
	 -- self == listbox item
	local scrollbarWidth = 0
	if self:getScrollHeight() > self:getHeight() then
		scrollbarWidth = self.vscroll:getWidth()
	end
	self:drawRect(0,y, self:getWidth() - scrollbarWidth, item.height-1, 0.8, 0.0, 0.0, 0.0)
	local isMouseOver = self.mouseoverselected == item.index and not self:isMouseOverScrollBar()
	if self.selected == item.index then
		self:drawRect(0, (y), self:getWidth() - scrollbarWidth, item.height-1, 0.3, 0.7, 0.35, 0.15);
	elseif isMouseOver then
		self:drawRect(1, y + 1, self:getWidth() - 2, item.height - 2, 0.95, 0.05, 0.05, 0.05);
	end
	self:drawRectBorder(0, (y), self:getWidth() - scrollbarWidth, item.height-1, 0.5, self.borderColor.r, self.borderColor.g, self.borderColor.b);

--	local richText = item.richText
--	local richTextWidth = self.width - scrollbarWidth - MapSelecter.padXY - MapSelecter.imageSize - MapSelecter.padXY * 2
--	if richText:getWidth() ~= richTextWidth then
--		richText:setWidth(richTextWidth)
--		richText:paginate()
--	end
--	richText:render(MapSelecter.padXY + MapSelecter.imageSize + MapSelecter.padXY, y + 32 + 8, self)

	local fontHgt = getTextManager():getFontFromEnum(UIFont.NewLarge):getLineHeight()
	self:drawText(item.text, 20, (y)+(item.height - fontHgt)/2, 0.9, 0.9, 0.9, 0.9, UIFont.NewLarge);
--	if item.worldimage ~= nil then
--		self:drawTexture(item.worldimage, MapSelecter.padXY, y+MapSelecter.padXY, 1, 1, 1, 1);
--	end

	y = y + item.height;

	return y;
end

function MapSelecter:render()
    local selectedItem = self.listbox.items[self.listbox.selected];

    local thumbHeight = 64;
    if selectedItem.worldimage ~= nil then
        thumbHeight = selectedItem.worldimage:getHeight();
        local BreakPoint = ((self.width/4)*3) - selectedItem.worldimage:getHeight()/2;
        self:drawTexture(selectedItem.worldimage, BreakPoint, self.startY, 1, 1, 1, 1);
        self:drawRectBorder( BreakPoint, self.startY, selectedItem.worldimage:getWidth(), selectedItem.worldimage:getHeight(), 0.3, 1, 1, 1);
        --        self:drawTexture(item.worldimage, MapSelecter.padXY, y+MapSelecter.padXY, 1, 1, 1, 1);
    end
    local descRectWidth = self.width - 37 - (self.width/2 + 30)
    local descRectHeight = self.height - 60 - (self.startY + thumbHeight + 10)
    self.richText:setX(self.width/2 + 30)
    self.richText:setY(self.startY + thumbHeight + 10)
    self.richText:setWidth(descRectWidth)
    self.richText:setHeight(descRectHeight)
    self.richText:setVisible(true);
    self.richText.text = selectedItem.desc;
    self.richText:paginate();
    self:drawRectBorder( self.width/2 + 30, self.startY + thumbHeight + 10, self.richText:getWidth(), self.richText:getHeight(), 0.3, 1, 1, 1);
end

function MapSelecter:onOptionMouseDown(button, x, y)
	if button.internal == "BACK" then
		self:setVisible(false);
		MainScreen.instance.mapSelect:setVisible(false);
        if getWorld():getGameMode() == "Multiplayer" then
            MainScreen.instance.joinServer:setVisible(true);
            ServerList.instance.connecting = false;
            ServerList.instance.playButton:setEnable(true);
            disconnect();
            ServerList.instance.NoLabel = true;
            return;
        end
		if #WorldScreen.instance.listbox.items == 0 then
--			MainScreen.instance.bottomPanel:setVisible(true);
            MainScreen.instance.soloScreen:setVisible(true, self.joyfocus);
--            if self.joyfocus then
--                self.joyfocus.focus = MainScreen.instance;
--                updateJoypadFocus(self.joyfocus);
--            end
		else
--			MainScreen.instance.worldScreen:setVisible(true, self.joyfocus);
            MainScreen.instance.loadScreen:setSaveGamesList();
            MainScreen.instance.loadScreen:setVisible(true, self.joyfocus);
		end
	end
	if button.internal == "NEXT" then
		self:clickNext();
	end
end

function MapSelecter:onDblClickMap()
	if MainScreen.instance.mapSelect.playButton:isEnabled() then
		MapSelecter.clickNext(MapSelecter.instance);
	end
end

function MapSelecter:clickNext()
    local map = self.listbox.items[self.listbox.selected].dir;
    MainScreen.instance.charCreationProfession.map = map:gsub("%s", ""):gsub(",", "");
	getWorld():setMap(map);
	if getWorld():getGameMode() == "Sandbox" then
		MainScreen.instance.mapSelect:setVisible(false);
		if MapSpawnSelect.instance:hasChoices() then
			MapSpawnSelect.instance:fillList()
			MapSpawnSelect.instance.previousScreen = "MapSelecter"
			MapSpawnSelect.instance:setVisible(true, self.joyfocus)
		else
			MapSpawnSelect.instance:useDefaultSpawnRegion()
			MainScreen.instance.sandOptions:setVisible(true, self.joyfocus)
		end
        if MainScreen.instance.mapSelect.createWorld then
		    getWorld():setWorld(sanitizeWorldName(self.textEntry:getText()));
        end
	else
		MainScreen.instance.mapSelect:setVisible(false);
		if MapSpawnSelect.instance:hasChoices() then
			MapSpawnSelect.instance:fillList()
			MapSpawnSelect.instance.previousScreen = "MapSelecter"
			MapSpawnSelect.instance:setVisible(true, self.joyfocus)
		else
			MainScreen.instance.charCreationMain:setVisible(true, self.joyfocus)
		end
        if MainScreen.instance.mapSelect.createWorld then
		    getWorld():setWorld(sanitizeWorldName(self.textEntry:getText()));
        end
    end
	MainScreen.instance.charCreationProfession.doSpawnPoint = true;
end

function MapSelecter:disableBtn()
	-- first : do we enter a name for the save
	if self.textEntry:getText() == nil or luautils.trim(self.textEntry:getText()) == "" then
		self.playButton:setEnable(false);
	else
		self.playButton:setEnable(true);
	end

	-- next : is the name already exist for another save ?
    if MainScreen.instance.mapSelect.createWorld then
        local dirs = getSaveDirectoryTable();
        for i, k in ipairs(dirs) do
            if luautils.trim(self.textEntry:getText()) == k then
                self.playButton:setEnable(false);
                break;
            end
        end
    end
end

function MapSelecter:create()

	self.backButton = ISButton:new(16, self.height-30, 100, 25, getText("UI_btn_back"), self, MapSelecter.onOptionMouseDown);
	self.backButton.internal = "BACK";
	self.backButton:initialise();
	self.backButton:instantiate();
	self.backButton:setAnchorLeft(true);
	self.backButton:setAnchorTop(false);
	self.backButton:setAnchorBottom(true);
	self.backButton.borderColor = {r=1, g=1, b=1, a=0.1};
	self:addChild(self.backButton);

	self.playButton = ISButton:new(self.width - 116, self.height-30, 100, 25, getText("UI_btn_next"), self, MapSelecter.onOptionMouseDown);
	self.playButton.internal = "NEXT";
	self.playButton:initialise();
	self.playButton:instantiate();
	self.playButton:setAnchorLeft(false);
	self.playButton:setAnchorRight(true);
	self.playButton:setAnchorTop(false);
	self.playButton:setAnchorBottom(true);
	self.playButton:setEnable(true); -- sets the hard-coded border color
	self:addChild(self.playButton);


	self.textEntryLabel = ISLabel:new(20, 48, 50, getText("UI_mapselecter_savename"), 1, 1, 1, 1, UIFont.Medium, true);
	self.textEntryLabel:initialise();
	self.textEntryLabel:instantiate();
	self.textEntryLabel:setAnchorLeft(true);
	self.textEntryLabel:setAnchorRight(true);
	self.textEntryLabel:setAnchorTop(false);
	self.textEntryLabel:setAnchorBottom(false);
	self:addChild(self.textEntryLabel);

	local mediumFontHgt = getTextManager():MeasureFont(UIFont.Medium) -- FIXME, used by ISLabel
	local inset = 2
	self.textEntry = ISTextEntryBox:new("", self.textEntryLabel:getRight() + 17, self.textEntryLabel.y + (self.textEntryLabel.height - mediumFontHgt) / 2 - inset, self.width-(self.textEntryLabel:getRight() + 17) - 16, 18);
	self.textEntry.font = UIFont.Medium
	self.textEntry:initialise();
	self.textEntry:instantiate();
	self.textEntry:setAnchorLeft(true);
	self.textEntry:setAnchorRight(true);
	self.textEntry:setAnchorTop(true);
	self.textEntry:setAnchorBottom(false);
	self:addChild(self.textEntry);
	local sdf = SimpleDateFormat.new("dd-MM-yyyy_hh-mm-ss");
	self.textEntry:setText(sdf:format(Calendar.getInstance():getTime()));

	self.listbox = ISScrollingListBox:new(16, self.startY, self.width/2, self.height-30-30-self.startY);
	self.listbox:initialise();
	self.listbox:instantiate();
	self.listbox:setAnchorLeft(true);
--	self.listbox:setAnchorRight(true);
	self.listbox:setAnchorTop(true);
	self.listbox:setAnchorBottom(true);
	self.listbox.doDrawItem = MapSelecter.drawMap;
	self:addChild(self.listbox);
	self.listbox.itemheight = 50;
	self.listbox:setOnMouseDoubleClick(self, MapSelecter.onDblClickMap)
	self.listbox.backgroundColor.a = 0

    self.richText = ISRichTextPanel:new(16, 10, 500,200);
    self.richText.marginRight = 20
    self.richText.autosetheight = false;
    self.richText.clip = true
    self.richText:initialise();
    self.richText.background = false;
    self.richText:setAnchorBottom(true);
    self.richText:setAnchorRight(true);
    self.richText:setVisible(false);
    self:addChild(self.richText);
    self.richText:addScrollBars()

--	self:addScrollBars();

	self:fillList()
end

MapSelecter.onKeyPressed = function(key)
	if key == 28 and MainScreen.instance and MainScreen.instance.mapSelect and MainScreen.instance.mapSelect:getIsVisible() and MainScreen.instance.mapSelect.playButton:isEnabled() then -- pressing enter is like clicking on next
		MapSelecter.clickNext(MapSelecter.instance);
	end
end

function MapSelecter:onGainJoypadFocus(joypadData)
    ISPanelJoypad.onGainJoypadFocus(self, joypadData);
    joypadData.focus = self.listbox;
    updateJoypadFocus(joypadData);
    self.listbox:setISButtonForA(self.playButton);
    self.listbox:setISButtonForB(self.backButton);
end

function MapSelecter:fillList()
	self.listbox:clear()
	local dirs = getMapDirectoryTable();
	local textHgtWithSB = 0
	local textHgtWithoutSB = 0
	local textLeft = MapSelecter.padXY + MapSelecter.imageSize + MapSelecter.padXY
	local scrollbarWidth = self.listbox.vscroll:getWidth()
	local count = 0
	local heightWithSB = {}
	local heightWithoutSB = {}
	local widthWithoutSB = self.listbox.width - MapSelecter.padXY - textLeft
--	local richText = ISRichTextLayout:new(widthWithoutSB)
--	richText:initialise()
--	for i, k in ipairs(dirs) do
--		local info = getMapInfo(k)
--		if info then
--			-- Calculate the text height with and without a scrollbar
--			richText:setText(info.description or "NO DESCRIPTION")
--			richText:setWidth(widthWithoutSB - scrollbarWidth)
--			richText:paginate()
--			textHgtWithSB = math.max(textHgtWithSB, richText:getHeight())
--			heightWithSB[i] = richText:getHeight()
--
--			richText:setWidth(widthWithoutSB)
--			richText:paginate()
--			textHgtWithoutSB = math.max(textHgtWithoutSB, richText:getHeight())
--			heightWithoutSB[i] = richText:getHeight()
--
--			count = count + 1
--		end
--	end
--	local minHgt = MapSelecter.padXY + MapSelecter.imageSize + MapSelecter.padXY
--	local itemHgt = math.max(minHgt, 40 + textHgtWithoutSB + MapSelecter.padXY)
--	local heights = heightWithoutSB
--	local width = widthWithoutSB
--	if count * itemHgt > self.listbox:getHeight() then
--		itemHgt = math.max(minHgt, 40 + textHgtWithSB + MapSelecter.padXY)
--		heights = heightWithSB
--		width = width - scrollbarWidth
--	end
--	self.listbox.itemheight = itemHgt
	for i, k in ipairs(dirs) do
		local info = getMapInfo(k)
		if info then
			local item = self.listbox:addItem(info.title or "NO TITLE", nil);
--			item.height = math.max(minHgt, 40 + heights[i] + MapSelecter.padXY)
			item.dir = k
			item.desc = info.description or "NO DESCRIPTION"
			item.worldimage = info.thumb
--			item.richText = ISRichTextLayout:new(width)
--			item.richText:initialise()
--			item.richText:setText(item.desc)
--			item.richText:paginate()
		end
	end
end

function MapSelecter:onResolutionChange(oldw, oldh, neww, newh)
	self.listbox:setWidth(self.width / 2)
end

function MapSelecter:new (x, y, width, height)
	local o = {}
	--o.data = {}
	o = ISPanelJoypad:new(x, y, width, height);
	MapSelecter.instance = o;
	setmetatable(o, self)
	self.__index = self
	o.x = x;
	o.y = y;
	o.backgroundColor = {r=0, g=0, b=0, a=0.3};
	o.borderColor = {r=1, g=1, b=1, a=0.2};
	o.width = width;
	o.height = height;
	o.anchorLeft = true;
	o.anchorRight = false;
	o.anchorTop = true;
	o.anchorBottom = false;
	o.addY = 0;
    o.startY = 110;
	return o
end

Events.OnKeyPressed.Add(MapSelecter.onKeyPressed);
