from ctyun.man.model.request import Request
import xml.sax
from ctyun.util.utils import XMLHandler
from ctyun.result import Result
from ctyun.result import ResponseHeader
from xml.dom.minidom import parseString
from ctyun.man.model.baseStatistics import BaseStatistics


class GetConnectionRequest(Request):
    def __init__(self, begin_date=None, end_date=None, bucket=None):
        self.BeginDate = begin_date
        self.EndDate = end_date
        self.Bucket = bucket

    def get_params(self):
        params = {"Action": "GetConnection"}
        if self.BeginDate is not None:
            params['BeginDate'] = self.BeginDate
        if self.EndDate is not None:
            params['EndDate'] = self.EndDate
        if self.Bucket is not None:
            params['BucketName'] = self.Bucket
        return params


class ConnectionStatistics(BaseStatistics):
    OBJ_TEMPLATE = (
            "\n    Connection Statistic {order}: \n"
            + "       Date: {date}, "
            + "       Connection: {Connection} "
            + "\n"
    )
    CONCURRENT_CONNECTION_KEYS = ["Connection"]

    def __init__(self, statistic, order):
        super().__init__()
        self.date = self.get_text(statistic, "Date")
        self.connection = self.get_text(statistic, "Connection")
        self.msg = self.format_message(statistic, order)

    def format_message(self, statistic, order):
        message_parts = [self.OBJ_TEMPLATE.format(
            order=order,
            date=self.date,
            Connection=self.connection
        )]
        return ''.join(message_parts)

    def to_string(self):
        return self.msg


class GetConnectionResult(Result):
    OBJ_TEMPLATE = (
            "Get Connection Result: \n"
            + " UserName: {UserName}, "
            + " BucketName: {BucketName}, "
            + " \n Statistics: {Statistics} "
    )

    def set_header(self, header):
        self.header = header

    def get_header(self):
        return self.header

    def __init__(self):
        self.UserName = None
        self.BucketName = None
        self.RegionCount = 0
        self.RegionList = []
        self.Regions = []
        self.xmlResp = ""
        self.msg = ""
        self.header = ResponseHeader()

    def parse(self, xml_response):
        xh = XMLHandler()
        xml.sax.parseString(xml_response, xh)
        self.xmlResp = xml_response
        result = xh.getDict()
        self.UserName = result['UserName']
        if result.__contains__('BucketName'):
            self.BucketName = result['BucketName']

        region_list_msg = ""
        self.RegionList = parseString(xml_response).documentElement.getElementsByTagName("Region")
        ii = 0
        for region in self.RegionList:
            region_list_msg += "Region Name:" + region.getElementsByTagName("Name")[0].childNodes[0].data
            Datas = region.getElementsByTagName("Data")
            for data in Datas:
                one_data = ConnectionStatistics(data, ii)
                self.Regions.append(one_data)
                ii = ii + 1
                region_list_msg += one_data.to_string()

        self.msg = self.OBJ_TEMPLATE.format(
            UserName=self.UserName,
            BucketName=self.BucketName,
            Statistics=region_list_msg,
        )

    def get_xml_resp(self):
        return self.xmlResp

    def to_string(self):
        return self.msg
