local I = {}

function I.create ()

	gLuaHandler.registerDelegateCallbacks(I, Delegates.PartyChanged, 0, I.onPartyChangedEvent)

	gParty.clear()
	I.ship = LuaShip(gParty.createShip({
		type = ShipType.Chatellin
	}))

	I.window = LuaWindow(gGUI.createWindow({
		width = 358,
		height = 280,
		verticalAlignment = VerticalAlignment.Middle,
		id = "quickGWnd",
		title = "%quick_game_options_title"
	}))


  -- World size options

  gGUI.createText({
    parent = I.window.instance(),
    x = 10,
    y = 20,
    width = 100,
    height = 10,
    font = 5,
    color = 2,
    text = "%quick_game_world_size"
  })

  I.worldSizeList = LuaList(gGUI.createList({
    parent = I.window.instance(),
    x = 7,
    y = 30,
    width = 130,
    visibleRows = 3,
    selectionColor = 1,
    rowHeight = 12,
    selected = 1
  }))

	gGUI.createSeparator({
		parent = I.window.instance(),
		vertical = true,
		x = 139,
		y = 21,
		height = 100
	})

  local worldSizeListDataSource = LuaListDataSource(I.worldSizeList.getDataSource())

  worldSizeListDataSource.removeAllItems()
  worldSizeListDataSource.addItem({ key = "quick_game_world_size_1"})
  worldSizeListDataSource.addItem({ key = "quick_game_world_size_2"})
  worldSizeListDataSource.addItem({ key = "quick_game_world_size_3"})
  worldSizeListDataSource.addItem({ key = "quick_game_world_size_4"})
  worldSizeListDataSource.addItem({ key = "quick_game_world_size_5"})


  -- Landmass options

  gGUI.createText({
    parent = I.window.instance(),
    x = 149,
    y = 20,
    width = 95,
    height = 10,
    font = 5,
    color = 2,
    text = "%quick_game_landmass"
  })

  I.landMassList = LuaList(gGUI.createList({
    parent = I.window.instance(),
    x = 146,
    y = 30,
    width = 75,
    visibleRows = 3,
    selectionColor = 1,
    rowHeight = 12,
    selected = 1
  }))

	gGUI.createSeparator({
		parent = I.window.instance(),
		vertical = true,
		x = 223,
		y = 21,
		height = 100
	})

  local landMassListDataSource = LuaListDataSource(I.landMassList.getDataSource())

  landMassListDataSource.removeAllItems()
  landMassListDataSource.addItem({ key = "quick_game_landmass_1"})
  landMassListDataSource.addItem({ key = "quick_game_landmass_2"})
  landMassListDataSource.addItem({ key = "quick_game_landmass_3"})


  -- Stuff to discover

  gGUI.createText({
    parent = I.window.instance(),
    x = 233,
    y = 20,
    width = 190,
    height = 10,
    font = 5,
    color = 2,
    text = "%quick_game_discoverables"
  })

  I.numberOfLocationsList = LuaList(gGUI.createList({
    parent = I.window.instance(),
    x = 230,
    y = 30,
    width = 121,
    visibleRows = 3,
    selectionColor = 1,
    rowHeight = 12,
    selected = 1
  }))

  local numberOfLocationsListDataSource = LuaListDataSource(I.numberOfLocationsList.getDataSource())

  numberOfLocationsListDataSource.removeAllItems()
  numberOfLocationsListDataSource.addItem({ key = "quick_game_discoverables_1"})
  numberOfLocationsListDataSource.addItem({ key = "quick_game_discoverables_2"})
  numberOfLocationsListDataSource.addItem({ key = "quick_game_discoverables_3"})


  gGUI.createText({
    parent = I.window.instance(),
    x = 10,
    y = 73,
    width = 190,
    height = 10,
    font = 5,
    color = 2,
    text = "%quick_game_starting_season"
  })

  I.startingSeasonList = LuaList(gGUI.createList({
    parent = I.window.instance(),
    x = 7,
    y = 83,
    width = 130,
    visibleRows = 3,
    selectionColor = 1,
    rowHeight = 12,
    selected = 0
  }))


  local startingSeasonListDataSource = LuaListDataSource(I.startingSeasonList.getDataSource())

  startingSeasonListDataSource.removeAllItems()
  startingSeasonListDataSource.addItem({ key = "quick_game_season_1"})
  startingSeasonListDataSource.addItem({ key = "quick_game_season_2"})
  startingSeasonListDataSource.addItem({ key = "quick_game_season_3"})



  --
  -- Party section

  gGUI.createTitleBar({
    parent = I.window.instance(),
    y = 125,
    text = "%quick_game_party"
  })

  gGUI.createText({
    parent = I.window.instance(),
    x = 10,
    y = 138,
    width = 100,
    height = 10,
    font = 5,
    color = 2,
    text = "%quick_game_members"
  })

  I.memberList = LuaList(gGUI.createList({
    parent = I.window.instance(),
    x = 7,
    y = 149,
    width = 130,
    visibleRows = 6,
    selectionColor = 1,
    rowHeight = 14,
    selected = 0,
		outline = true
  }))

	gGUI.createSeparator({
		parent = I.window.instance(),
		vertical = true,
		x = 139,
		y = 138,
		height = 124
	})


	local newCharacterButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = 6,
		y = 236,
		width = 24,
		height = 24,
		sprite = gSpriteManager.getSprite(198, SpriteGroup.GUI)
	}))

	local removeCharacterButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = 31,
		y = 236,
		width = 24,
		height = 24,
		sprite = gSpriteManager.getSprite(199, SpriteGroup.GUI)
	}))


	newCharacterButton.onClick(function()
		gGame.showCharacterCreation()
	end)

	removeCharacterButton.onClick(function()
		if gParty.getMemberCount() == 0 then
			return
		end
		local params = LuaPlayerParams(LuaPlayer(gParty.getPlayer(I.memberList.getSelectedRow())).getParams())
		LuaWindow(gGUI.showMessageBox({
			type = MessageBoxType.Confirmation,
			title = gUtils.translate("dismiss_member_confirm_title"),
			text = string.format(gUtils.translate("dismiss_member_confirm_msg"), params.name())
		})).onClose(function(buttonType)
			print("On Window Close")
			if buttonType == WindowClose.YesButton then
				gParty.dismissMember(I.memberList.getSelectedRow())
				I.populateMemberList()
			end
		end)
	end)


  gGUI.createText({
    parent = I.window.instance(),
    x = 149,
    y = 138,
    width = 100,
    height = 10,
    font = 5,
    color = 2,
    text = "%quick_game_gear"
  })

	I.gearGrid = LuaImage(gGUI.createImage({
		parent = I.window.instance(),
		x = 145,
		y = 148,
		width = 205,
		height = 86,
		sprite = gSpriteManager.getSprite(200, SpriteGroup.GUI)
	}))

	local changeGearButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = 145,
		y = 236,
		width = 24,
		height = 24,
		sprite = gSpriteManager.getSprite(198, SpriteGroup.GUI)
	}))

	gGUI.createButton({
		parent = I.window.instance(),
		x = 170,
		y = 236,
		width = 24,
		height = 24,
		sprite = gSpriteManager.getSprite(199, SpriteGroup.GUI)
	})

	changeGearButton.onClick(function()
		I.showGearList()
	end)


	local cancelButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = I.window.getWidth() / 2 - 143,
		y = I.window.getHeight() - 13,
		width = 140,
		height = 18,
		title = "%cancel_button"
	}))

	cancelButton.onClick(I.close)


	local startButton = LuaButton(gGUI.createButton({
		parent = I.window.instance(),
		x = I.window.getWidth() / 2 + 3,
		y = I.window.getHeight() - 13,
		width = 140,
		height = 18,
		title = "%quick_game_begin_button"
	}))

	startButton.onClick(function()

		if gParty.getMemberCount() == 0 then
			gGUI.showInformation({key = "sailing_out_no_party"})
			return
		end

		local sizeIndex = I.worldSizeList.getSelectedRow() + 1
		local landmassIndex = I.landMassList.getSelectedRow() + 1

		-- Sizes need to be divisable by 128
		local worldSizes = {{1024, 1024}, {2048, 2048}, {3072, 3072}, {1024, 3072}, {3072, 1024}}
		local landmassOptions = {{5.1, 0.365}, {3.45, 0.25}, {3.0, 0.194}}
		local disocverables = {{30, 40}, {60, 80}, {90, 140}, {50, 75}, {50, 75}}

		print("Size index "..sizeIndex.." size: ", worldSizes[sizeIndex][1], worldSizes[sizeIndex][2])
		print("Landmass index "..landmassIndex.." size: ", landmassOptions[landmassIndex][1], landmassOptions[landmassIndex][2])



		gGame.generateWorld({
			width = worldSizes[sizeIndex][1],
			height = worldSizes[sizeIndex][2],
			-- Roughness
			perlinOctaves = 13,
			-- Higher number means less large slabs of terrain
			perlinFrequency = landmassOptions[landmassIndex][1],
			-- Perlin noise generated will range from -perlinAmplitude to perlinAmplitude
			perlinAmplitude = 16.0,
			-- The larger the value, the more of the noise values will be discarded
			-- resulting in less land. 0 would mean all of the world is terrain.
			perlinThreshold = landmassOptions[landmassIndex][2],
			-- Maximum number of temples and villages
			-- Depending on the landmass generated and placement the actual number may be smaller
			numberOfTemples = disocverables[sizeIndex][1],
			numberOfVillages = disocverables[sizeIndex][2],
			season = I.startingSeasonList.getSelectedRow()
		})
		I.close()
	end)

	I.populateMemberList()
	I.populateItemGrid()

end

function I.showGearList ()

	I.gearListWindow = LuaWindow(gGUI.createWindow({
		width = 200,
		height = 234,
		verticalAlignment = VerticalAlignment.Middle,
		id = "gearListWnd",
		title = "%quick_game_gear_window_title"
	}))

	I.gearList = LuaList(gGUI.createList({
		parent = I.gearListWindow.instance(),
		x = 7,
		y = 21,
		width = I.gearListWindow.getWidth() - 14,
		visibleRows = 12,
		selectionColor = 0,
		rowHeight = 16,
		outline = true
	}))

	I.gearList.onItemSelected(function(index, item)
		item = LuaListDataItem(item)
		local gearListItem = I.allGearItems[index+1]

		if gearListItem[3] == false then
			gearListItem[3] = true
			item.accessoryType(ListRowAccessory.CheckmarkDark)
			item.overwriteTextColorIndex(2)
		else
			gearListItem[3] = false
			item.accessoryType(ListRowAccessory.None)
			item.overwriteTextColorIndex(3)
		end
	end)


	local gearListDataSource = LuaListDataSource(I.gearList.getDataSource())

	gearListDataSource.removeAllItems();

	for i=1,#I.allGearItems do

		I.allGearItems[i][3] = false

		local str = gUtils.translate(I.allGearItems[i][1].name)
		if I.allGearItems[i][2] > 1 then
			str = str.." ("..string.format(gUtils.translate("format_fleet_cargo"), I.allGearItems[i][2])..")"
		end
		local lItem = LuaListDataItem(gearListDataSource.addItem({ text = str, icon = gSpriteManager.getSprite(I.allGearItems[i][1].index, SpriteGroup.Inventory) }))
	end


	local cancelButton = LuaButton(gGUI.createButton({
		parent = I.gearListWindow.instance(),
		x = I.gearListWindow.getWidth() / 2 - 83,
		y = I.gearListWindow.getHeight() - 13,
		width = 80,
		height = 18,
		title = "%cancel_button"
	}))

	local addButton = LuaButton(gGUI.createButton({
		parent = I.gearListWindow.instance(),
		x = I.gearListWindow.getWidth() / 2 + 3,
		y = I.gearListWindow.getHeight() - 13,
		width = 80,
		height = 18,
		title = "%add_button",
		sound = gSoundManager.getSound(6, SoundGroup.SFX)
	}))

	cancelButton.onClick(function()
		gGUI.scheduleForDeletion(I.gearListWindow.instance())
	end)

	addButton.onClick(function()
		local masterInventory = LuaInventory(I.ship.getInventory())
		for i=1,#I.allGearItems do
			if I.allGearItems[i][3] == true then
				local newInvItem = LuaInventoryItem(gUtils.createInventoryItem({
					primary = I.allGearItems[i][1].index,
					amount = I.allGearItems[i][2]
				}))
				masterInventory.addItem(newInvItem.instance())
			end
		end
		gGUI.scheduleForDeletion(I.gearListWindow.instance())
		I.populateItemGrid()
	end)

end

function I.close ()
	gLuaHandler.unregisterDelegateCallbacks(I)
	gGUI.scheduleForDeletion(I.window.instance())
	UI.Interfaces["quickgame"] = nil
	I = nil
end

function I.populateItemGrid ()
	I.gearGrid.removeChildren()
	local masterInventory = LuaInventory(I.ship.getInventory())
	print("Items in master inventory: "..masterInventory.countItems())
	local x, y = 0, 0
	for i=0,masterInventory.countItems()-1 do
		local invItem = LuaInventoryItem(masterInventory.getItemAtIndex(i))
		local itemButton = LuaButton(gGUI.createButton({
			parent = I.gearGrid.instance(),
			x = 1 + (x * 16) + (x * 1),
			y = 1 + (y * 16) + (y * 1),
			width = 16,
			height = 16,
			sprite = gSpriteManager.getSprite(invItem.type(), SpriteGroup.Inventory)
		}))
		x = x + 1
		if x == 12 then
			x = 0
			y = y + 1
		end
	end
end

function I.populateMemberList ()
  local memberListDataSource = LuaListDataSource(I.memberList.getDataSource())
	memberListDataSource.removeAllItems()
	for i=0,gParty.getMemberCount()-1 do
		local member = LuaPlayer(gParty.getPlayer(i))
		local params = LuaPlayerParams(member.getParams())
		memberListDataSource.addItem({ text = params.name() })
	end
end

function I.onPartyChangedEvent (args)
	I.populateMemberList()
	return false
end

UI.Interfaces["quickgame"] = I

I.allGearItems = {
	{ItemDefinitions.Axe, 					0, 		false},
	{ItemDefinitions.Flask, 				0, 		false},
	{ItemDefinitions.Tent, 					0, 		false},
	{ItemDefinitions.Pickaxe, 			0, 		false},
	{ItemDefinitions.Shovel, 				0, 		false},
	{ItemDefinitions.Saw, 					0, 		false},
	{ItemDefinitions.FishingRod, 		0, 		false},
	{ItemDefinitions.Binoculars, 		0, 		false},
	{ItemDefinitions.FreshWater, 		100,	false},
	{ItemDefinitions.DriedMeat, 		50, 	false},
	{ItemDefinitions.Bread, 				25, 	false},
	{ItemDefinitions.Biscuits, 			25,	 	false},
	{ItemDefinitions.Knife, 				0, 		false},
	{ItemDefinitions.Sword, 				0, 		false},
	{ItemDefinitions.Bow, 					0, 		false},
	{ItemDefinitions.BattleAxe, 		0, 		false},
	{ItemDefinitions.ArmorLeather, 	0, 		false},
	{ItemDefinitions.ArmorMail, 		0, 		false},
	{ItemDefinitions.Wood, 					20, 	false},
}
