# ###################################################
# Copyright (C) 2008-2017 The Unknown Horizons Team
# team@unknown-horizons.org
# This file is part of Unknown Horizons.
#
# Unknown Horizons is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the
# Free Software Foundation, Inc.,
# 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
# ###################################################

from typing import List

from horizons.component import Component
from horizons.util.changelistener import ChangeListener


class NamedComponent(Component):
	"""An object that has a special name. "Special" means, that it's not (only) autogenerated."""

	NAME = "namedcomponent"

	names_used = [] # type: List[str]

	def __init__(self, name=None):
		super().__init__()
		self.name = name

	def initialize(self):
		self.set_name(self.name)

	def set_name(self, name=None):
		"""Actually sets the name."""
		if self.name is not None and self.name in NamedComponent.names_used:
			NamedComponent.names_used.remove(self.name)
		if name is None:
			name = self.get_default_name()
		self.name = name
		NamedComponent.names_used.append(self.name)
		if isinstance(self.instance, ChangeListener):
			self.instance._changed()

	def _possible_names(self):
		return ['object_{}'.format(self.instance.worldid)]

	def get_default_name(self):
		available_names = [name for name in self._possible_names() if name not in NamedComponent.names_used]

		if available_names != []:
			return self.session.random.choice(available_names)
		else:
			newname = self.session.random.choice(self._possible_names())
			index = 2
			while "{newname} {index}".format(newname=newname, index=index) in NamedComponent.names_used:
				index += 1
			return "{newname} {index}".format(newname=newname, index=index)

	def save(self, db):
		super().save(db)
		db("INSERT INTO name (rowid, name) VALUES(?, ?)", self.instance.worldid, self.name)

	def load(self, db, worldid):
		super().load(db, worldid)
		self.name = None
		name = db("SELECT name FROM name WHERE rowid = ?", worldid)[0][0]
		# We need unicode strings as the name is displayed on screen.
		self.set_name(name)

	@classmethod
	def reset(cls):
		cls.names_used = []


class ShipNameComponent(NamedComponent):

	def _possible_names(self):
		names = self.session.db("SELECT name FROM shipnames WHERE for_player = 1")
		return [x[0] for x in names]


class PirateShipNameComponent(NamedComponent):

	def _possible_names(self):
		names = self.session.db("SELECT name FROM shipnames WHERE for_pirate = 1")
		return [x[0] for x in names]


class SettlementNameComponent(NamedComponent):

	def _possible_names(self):
		names = self.session.db("SELECT name FROM citynames WHERE for_player = 1")
		return [x[0] for x in names]


class SoldierNameComponent(NamedComponent):

	def _possible_names(self):
		names = self.session.db("SELECT name FROM groundunitnames WHERE for_soldier = 1")
		return [x[0] for x in names]


class InhabitantNameComponent(NamedComponent):

	def _possible_names(self):
		names = self.session.db("SELECT name FROM groundunitnames WHERE for_inhabitant = 1")
		return [x[0] for x in names]
