from parallels.common.utils import plesk_utils
from parallels.common.import_api.import_api import UserAlreadyExistsException, LoginIsInvalidException
from parallels.utils import safe_string_repr

def plesk_unix_change_sysuser_login(runner, subscription_name, sysuser_login):
	cmd_str = u"/usr/local/psa/admin/plib/api-cli/domain.php --update %s -login %s" % (
		subscription_name.encode('idna'), 
		sysuser_login
	)
	exit_code, stdout_content, stderr_content = runner.sh_unchecked(cmd_str)
	_parse_change_sysuser_login_output(cmd_str, sysuser_login, exit_code, stdout_content, stderr_content)

def plesk_windows_change_sysuser_login(runner, subscription_name, sysuser_login):
	cmd_str = ur"%s\bin\domain --update %s -login %s" % (
		plesk_utils.get_windows_plesk_dir(runner), 
		subscription_name.encode('idna'), sysuser_login
	)
	exit_code, stdout_content, stderr_content = runner.sh_unchecked(cmd_str)
	_parse_change_sysuser_login_output(cmd_str, sysuser_login, exit_code, stdout_content, stderr_content)

def _parse_change_sysuser_login_output(cmd_str, sysuser_login, exit_code, stdout_content, stderr_content):
	if exit_code != 0:
		if u"User %s already exists." % (sysuser_login,) in stderr_content:
			raise UserAlreadyExistsException()
		elif u"Some fields are empty or contain an improper value" in stderr_content and u"'login'" in stderr_content:
			raise LoginIsInvalidException()
		else:
			raise Exception(
				u"Command '%s' failed with exit code %d\n"
				u"stdout: %s\nstderr: %s"
				% (cmd_str, exit_code, safe_string_repr(stdout_content), safe_string_repr(stderr_content))
			)

def plesk_unix_get_dedicated_app_pool_user(runner, subscription_name):
	get_new_iis_app_user_cmd = \
		u"mysql --silent --skip-column-names -u admin -p`cat /etc/psa/.psa.shadow` psa -e \"%s\"" % (
			_get_dedicated_app_pool_user_query(subscription_name.encode('idna')),
		)
	return runner.sh(get_new_iis_app_user_cmd).strip()

def plesk_windows_get_dedicated_app_pool_user(runner, subscription_name):
	plesk_dir = plesk_utils.get_windows_plesk_dir(runner)
	get_new_iis_app_user_cmd = \
		ur'%s\admin\bin\dbclient --direct-sql --sql="%s"' % (
			plesk_dir, _get_dedicated_app_pool_user_query(subscription_name.encode('idna')),
		)
	lines = runner.sh(get_new_iis_app_user_cmd).strip().split("\n")
	if len(lines) > 1:
		return lines[1].strip()
	else:
		return None

def _get_dedicated_app_pool_user_query(subscription_name):
	return u"SELECT identity FROM domains " + \
			u"JOIN IisAppPools ON IisAppPools.ownerType = 'domain' AND IisAppPools.ownerId = domains.id " + \
			u"WHERE domains.name = '%s'" % (subscription_name,)
