from collections import defaultdict
from parallels.core.utils.yaml_utils import read_yaml, write_yaml


class MoveState(object):
	def __init__(self):
		# first key - subscription name, 
		# second key - operation name 
		# value - operation status (True for success, False for failure)
		self.state = defaultdict(dict) 

	def set_success(self, subscription_name, command):
		self.state[subscription_name][command] = True

	def set_fail(self, subscription_name, command):
		self.state[subscription_name][command] = False

	def was_executed(self, subscription_name, command):
		return command in self.state[subscription_name]

	def was_command_failed(self, subscription_name, command):
		return self.was_executed(subscription_name, command) and self.state[subscription_name][command] == False

	def was_failed(self, subscription_name, commands_to_check=None):
		return not all([
			status for command, status in self.state[subscription_name].iteritems() 
			if commands_to_check is None or command in commands_to_check
		])


class MoveStateFile(MoveState):
	def __init__(self, filename):
		self.filename = filename
		self.state = read_yaml(filename, file_may_be_absent=True, default=defaultdict(dict))

	def set_success(self, *args, **kwargs):
		super(MoveStateFile, self).set_success(*args, **kwargs)	
		self._save_state()

	def set_fail(self, *args, **kwargs):
		super(MoveStateFile, self).set_fail(*args, **kwargs)
		self._save_state()

	def _save_state(self):
		write_yaml(self.filename, self.state)
