import hashlib, json, os
from pyna.base.Settings import Settings
from pyna.core.Packager import Packager
from pyna.core.NodeList import NodeList
from pyna.ui.PynaDisplay import PynaDisplay

class Manager(Settings):
	'''
	Manages all things related to other nodes and configuration settings
	'''

	def __init__(self, alias, location, port):
		super().__init__(alias)
		self.most_recent_whisperer = None
		self.location = '{0}:{1}'.format(location, port)
		self.node_list = NodeList()
		self.load()

	def load(self):
		'''Load all configuration settings and nodes'''
		config_filename = self.config_path('config.json')
		config = json.load(open(config_filename, 'r'))

		self.version = config['version']
		self.node_list.load()

	def whisper_toggle(self, target):
		'''Toggles between whispering and all chatting as default command'''
		if self.default_command == 'chat':
			self.default_command = 'whisperlock'
			if target is '':
				target = self.most_recent_whisperer
			self.whisper_lock_target = target
			return

		self.default_command = 'chat'

	def create_packager(self):
		'''Create a packager from our config settings'''
		args = {"alias": self.alias, "location": self.location, "uid": self.uid}
		return Packager(self.version, args)

	def get_node_hash(self):
		'''Create a Node Hash for nodeListHash command'''
		# create a list of publickeys
		publickeys = self.node_list.hash()

		# actually encode
		hashed = hashlib.sha512()
		hashed.update(publickeys.encode('utf-8'))
		return hashed.hexdigest()
