from collections import namedtuple
from datetime import datetime

from .. import core
from parallels.utils.xml import elem

SiteInfo = namedtuple('SiteInfo', (
	'gen_info',
))

SiteGenInfo = namedtuple('SiteGenInfo', (
	'creation_date', 'name', 'ascii_name', 'status', 'real_size', 'dns_ip_address',
	'htype', 'guid', 'webspace_guid',
))


class SiteOperator(object):
	class Dataset(object):
		GEN_INFO = 'gen_info'
		# Not implemented: 'hosting', 'stat', 'prefs', 'disk_usage'

		values = [GEN_INFO]
	
	FilterAll = core.FilterAll
	FilterByName = core.declare_filter('FilterByName', 'name')
	FilterById = core.declare_filter('FilterById', 'id')
	FilterByParentId = core.declare_filter('FilterByParentId', 'parent-id')
	FilterByParentName = core.declare_filter('FilterByParentName', 'parent-name')
	FilterByGuid = core.declare_filter('FilterByGuid', 'guid')
	FilterByParentGuid = core.declare_filter('FilterByParentGuid', 'parent-guid')

	class Get(core.operation_with_filter('Get', ('dataset',))):
		operator_name = 'site'
		operation_name = 'get'
		min_api_version = '1.6.3.0'
		max_api_version = None

		def data_xml(self):
			return [
				elem('dataset', [elem(value) for value in SiteOperator.Dataset.values if value in self.dataset])
			]
			
		@classmethod
		def parse(cls, elem):
			return core.filter_owner_not_found_error(core.parse_result_set(elem, cls._parse_data, 'id'))
		
		@classmethod
		def _parse_data(cls, elem):
			site_id = int(elem.findtext('id'))
			gen_info = cls._parse_gen_info(elem.find('data/gen_info'))
			
			return site_id, SiteInfo(gen_info)
			
		@classmethod
		def _parse_gen_info(cls, elem):
			return SiteGenInfo(
				creation_date=datetime.strptime(elem.findtext('cr_date'), '%Y-%m-%d'),
				name=elem.findtext('name'), ascii_name=elem.findtext('ascii-name'),
				status=int(elem.findtext('status')), real_size=int(elem.findtext('real_size')),
				dns_ip_address=elem.findtext('dns_ip_address'),
				htype=elem.findtext('htype'), guid=elem.findtext('guid'),
				webspace_guid=elem.findtext('webspace-guid'),
			)