import json
from urlparse import urlparse

from parallels.core.utils.common import split_list_by_count


class SHMContext(object):
	"""
	SHM context is a json-encoded dictionary with WHP DB and WHN access details.
	"""

	"""
	Maximum allowed env variable value length which can be passed through Plesk wrapper script to Plesk utils
	"""
	_PLESK_WRAPPER_MAX_ENV_VAR_VALUE_LEN = 200

	def __init__(self, ctx_string):
		self._raw = ctx_string
		self._ctx = json.loads(ctx_string)

		agent_url = self._ctx['serviceNode']['agentUrl']
		parts = urlparse(agent_url)

		self._ctx['serviceNodeIp'] = parts.hostname

	def get_as_env(self):
		"""
		Split SHM context json string into parts.
		Name each part like WHPCTXN where N is a part sequence number starting from 1.
		Returned dictionary can be used as additional ENV vars when calling pmmcli.

		:rtype: dict
		"""
		res = {}
		line_num = 1

		for chars in split_list_by_count(self._raw, self._PLESK_WRAPPER_MAX_ENV_VAR_VALUE_LEN):
			res['WHPCTX%s' % line_num] = ''.join(chars)
			line_num += 1

		return res

	def get_as_json(self):
		"""
		JSON encode SHM context so it can be passed to plesk utils STDIN.

		:rtype: basestring
		"""
		return json.dumps(self._ctx)

	def get_partition_path(self):
		return self._ctx['partitionPath']

	def get_web_sn_ip(self):
		return self._ctx['serviceNodeIp']
