require "level_editor/object_attributes"
require "level_editor/gui"

editorView = "room" --can be "off", "room", "world", "asset"
selectedColor = "red"

local bacSprite = love.graphics.newImage("art/_ui/bac.png")
local forwardSprite = love.graphics.newImage("art/_ui/forward.png")
local folderSprite = love.graphics.newImage("art/_ui/folder.png")
local cancelSprite = love.graphics.newImage("art/_ui/cancel.png")
local confirmSprite = love.graphics.newImage("art/_ui/confirm.png")

local selectedFolder = nil
local selectedAsset = nil
local selectedRoom = nil
local selectedRow = 1
local gameAssets = {}
local inputText = ""
local assetProperties = {}

local hierarchy = {}

local activeField = nil --this is for whenwe are doing text input things

local uiButtons = {}
local folderButtons = {}
local assetButtons = { {} } --table for rows so we can do stuff
local editingAssetButtons = {}

local labels = {}


function _initLevelEditor()
	gameAssets = getAllAssets()

	--create folder buttons
	local counter = 1

	for asset, attributes in pairs(gameAssets) do
		if not hierarchy[gameAssets[asset].directory] then
			hierarchy[gameAssets[asset].directory] = {}
		end
		table.insert(hierarchy[gameAssets[asset].directory], asset)
	end

	for folder, object in pairs(hierarchy) do
		local button = createUIElement{
			name = "folder",
			text = folder,
			x = 30,
			y = (sideBarBox.h - 50) * (counter / 15),
			sprite = folderSprite,
			onClic = {
				left = function(self)
					print("my asse")
					selectFolder(folder)
				end,
				right = function()

				end
			},
		}
		counter = counter + 1
		table.insert(folderButtons, button)
	end

	_addUIButton(createUIElement{
		name = "save",
		sprite = love.graphics.newImage("art/_ui/save.png"),	
		onClic = {
			left = function()
				if editorView == "room" then
					print("saveing!!")
					currentRoom:save() 
				end
			end,
			right = function()

			end
		},
		x = sideBarBox.w / 4,
		y = sideBarBox.h * (9 / 10)
	})

	_addUIButton(createUIElement{
		name = "world",
		sprite = love.graphics.newImage("art/_ui/world.png"),
		onClic = {
			left = function()
				print(editorView)
				if editorView == "room" then
					print("saveing!!")
					currentRoom:save() 
				end
			end,
			right = function()

			end
		},
		x = sideBarBox.w * (3 / 4),
		y = sideBarBox.h * (9 / 10)
	})

	for _, color in ipairs({"white", "red", "green", "blue"}) do
		_addUIButton(createUIElement{
			name = color,
			sprite = love.graphics.newImage("art/_ui/" ..  color .. ".png"),
			onClic = {
				left = function(self)
					if editorView == "room" then
						setSelectedColor(color)
					end
				end,
				right = function()

				end
			},
			x = sideBarBox.w * (_ / 5),
			y = sideBarBox.h * (8 / 10)
		})
	end

end

function setSelectedColor(color)
	selectedColor = color
end

function selectFolder(folder)
	selectedFolder = folder

	local bacButton = _addUIButton(createUIElement{
		name = "bacToFolderView",
		sprite = bacSprite,
		x = sideBarBox.w / 2,
		y = 37.5,
		onClic = {
			left = function(self)
				print(self, self.x)
				self = nil
				folderView(self)
			end,
			right = function(self) return end
		}
	}, "bacToFolderView")
	local row = 1
	local counter = 1
	local limit = 10

	for _, asset in pairs(hierarchy[selectedFolder]) do
		if counter % limit == 0 then
			counter = 1

			local forwardButton = createUIElement{
				name = "forward",
				sprite = forwardSprite,
				x = sideBarBox.w / 2,
				y = sideBarBox.h - 250,
				onClic = {
					left = function()
						selectedRow = selectedRow + 1
					end,
					right = function()

					end
				}
			}
			table.insert(assetButtons[row], forwardbutton)

			row = row + 1
			table.insert(assetButtons, {})
		end

		local sprites = {}

		for color, location in pairs(gameAssets[asset].sprites) do
			sprites[color] = love.graphics.newImage(location)
		end

		local assetButton = createUIElement{
			sprites = sprites,
			name = "asset",
			text = asset,
			x = 30,
			y = (sideBarBox.h - 225) * (counter / limit) + 20,
			onClic = {
				left = function()
					print(asset)
					selectAsset(asset)
				end,
				right = function()
					editAsset(asset)
				end
			}
		}
		table.insert(assetButtons[row], assetButton)
		counter = counter + 1
	end
end

function selectAsset(asset)
	print("selecting", asset)
	selectedAsset = asset
	print(selectedAsset)
end

function editAsset(asset)
	inputText = ""
	editorView = "asset"
	selectedAsset = asset

	assetProperties = gameAssets[selectedAsset]


	local cancelButton = createUIElement{
		name = "cancel",
		sprite = cancelSprite,
		x = sideBarBox.w / 3,
		y = sideBarBox.h - 75,
		onClic = {
			left = function(self)
				assetsView()
			end,
			right = function(self) return end
		}
	}

	local confirmButton = createUIElement{
		name = "confirm",
		sprite = confirmSprite,
		x = sideBarBox.w * 2 / 3,
		y = sideBarBox.h - 75,
		onClic = {
			left = function(self)
				saveAsset()
			end,
			right = function(self) return end
		}
	}

	editingAssetButtons[cancelButton] = cancelButton
	editingAssetButtons[confirmButton] = confirmButton

	local assetSprites = {}
	for color, path in pairs(assetProperties.sprites) do
		assetSprites[color] = love.graphics.newImage(path)
	end

	local assetButton = createUIElement{
		name = asset,
		sprites = assetSprites,
		x = sideBarBox.w / 2 - 18,
		y = 80,
	}	

	local classFieldLabel = {
		draw = function() love.graphics.printf("CLASS", 0, 125, sideBarBox.w, "center") end
	}

	labels[classFieldLabel] = classFieldLabel

	local classButton = createUIElement{
		name = "class",
		text = assetProperties.class or "",
		x = 25,
		y = 150,
		onClic = {
			left = function()
				activeField = "class"
			end
		}
	}

	local preloadLabel = {
		draw = function() love.graphics.printf("preload", 0, 225, sideBarBox.w, "center") end
	}

	labels[preloadLabel] = preloadLabel

	local preloadButton = createUIElement{
		name = "preload",
		text = tostring(assetProperties.preload),
		x = 25,
		y = 250,
		onClic = {
			left = function()
				assetProperties.preload = not assetProperties.preload
			end
		}
	}

	editingAssetButtons[assetButton] = assetButton
	editingAssetButtons.class = classButton
	editingAssetButtons.preload = preloadButton

end

function saveAsset()
	gameAssets[selectedAsset] = assetProperties
	local save = TSerial.pack(gameAssets, nil, true)
	love.filesystem.write("assets.prop", save)
	assetsView()
end


function _addUIButton(button, name)
	local index = name or button
	uiButtons[index] = button
end

function folderView()
	selectedRow = 1
	selectedFolder = nil
	assetButtons = {{}}
	uiButtons.bacToFolderView = nil
	labels = {}
end

function assetsView()
	editingAssetButtons = {}
	editorView = "room"
	labels = {}
end

function worldView()

end

function editorMouseHandler(x, y, button)
	if x > width then
		--we need to adjust for sidebar coords
		x = x - width

		if editorView == "room" then
			if not selectedFolder then
				for _, uiElement in pairs(folderButtons) do
					if uiElement:clicIsInBox(x, y) then
						uiElement:onClic(button)
						return
					end
				end
			else
				for _, uiElement in pairs(assetButtons[selectedRow]) do
					if uiElement:clicIsInBox(x, y) then
						uiElement:onClic(button)
						return
					end
				end
			end

			for _, uiElement in pairs(uiButtons) do
				if uiElement:clicIsInBox(x, y) then
					uiElement:onClic(button)
				end
			end
		elseif editorView == "asset" then
			for _, uiElement in pairs(editingAssetButtons) do
				if uiElement:clicIsInBox(x, y) then
					uiElement:onClic(button)
				end
			end
		end
	else
		-- click landed on the grid (game area): place the selected asset
		if editorView == "room" and button == 1 and selectedAsset then
			currentRoom:attemptPlace(selectedAsset, gameAssets[selectedAsset], x, y, selectedColor)
		end
	end
end

function editorTextHandler(text)
	if editorView == "asset" and activeField then
		inputText = text
		editingAssetButtons[activeField]:editText(text)
	end
end

function editorCompleteResponse()
	if editorView == "asset" then
		assetProperties[activeField] = inputText 
		print(assetProperties[activeField], "BLELERLLLRLRLRR")
	end
	print(activeField, assetProperties[activeField], "ass")
	activeField = nil
end

function sortAllAssets()
	setAll()
end

function createUIElement(t)
	return GUI:new(t)
end

function editorDraw()
	if editorView == "room" then
		for _, button in pairs(uiButtons) do
			button:draw()
		end
		if not selectedFolder then
			for _, folder in pairs(folderButtons) do
				folder:draw()
			end
		else
			for _, entity in ipairs(assetButtons[selectedRow]) do
				entity:draw()
			end
		end
	elseif editorView == "asset" then
		for _, button in pairs(editingAssetButtons) do
			button:draw()
		end
	end

	for _, label in pairs(labels) do
		label:draw()
	end
end
