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 GetUsageRequest(Request):
    def __init__(self, BeginDate=None, EndDate=None, Bucket=None):
        self.BeginDate = BeginDate
        self.EndDate = EndDate
        self.Bucket = Bucket

    def get_params(self):
        params = {"Action": "GetUsage"}
        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 GetUsageStatistics(BaseStatistics):
    OBJ_TEMPLATE = (
            "\n    Get Usage Region {order}: \n"
            + "       Region Name: {region_name}, "
            + "\n"
            + "       Date: {Date}, "
            + "\n"
            + "       Data:  "
            + "       Capacity: {Capacity}, "
            + "       Upload: {Upload} "
            + "       Download: {Download} "
            + "       DeleteFlow: {DeleteFlow} "
            + "       RoamUpload: {RoamUpload} "
            + "       RoamDownload: {RoamDownload} "
            + "       GetRequest: {GetRequest} "
            + "       HeadRequest: {HeadRequest} "
            + "       PutRequest: {PutRequest} "
            + "       PostRequest: {PostRequest} "
            + "       DeleteRequest: {DeleteRequest} "
            + "       OtherRequest: {OtherRequest} "
            + "       NonInternetUpload: {NonInternetUpload} "
            + "       NonInternetDownload: {NonInternetDownload} "
            + "       NonInternetDeleteFlow: {NonInternetDeleteFlow} "
            + "       NonInternetRoamUpload: {NonInternetRoamUpload} "
            + "       NonInternetRoamDownload: {NonInternetRoamDownload} "
            + "       NonInternetGetRequest: {NonInternetGetRequest} "
            + "       NonInternetHeadRequest: {NonInternetHeadRequest} "
            + "       NonInternetPutRequest: {NonInternetPutRequest} "
            + "       NonInternetPostRequest: {NonInternetPostRequest} "
            + "       NonInternetDeleteRequest: {NonInternetDeleteRequest} "
            + "       NonInternetOtherRequest: {NonInternetOtherRequest} "
            + "       SpamRequest: {SpamRequest} "
            + "       PornReviewFalse: {PornReviewFalse} "
            + "       PornReviewTrue: {PornReviewTrue} "
    )

    GET_USAGE_KEYS = [
        'Date', 'Capacity', 'Upload', 'Download', 'DeleteFlow', 'RoamUpload', 'RoamDownload',
        'GetRequest', 'HeadRequest', 'PutRequest', 'PostRequest', 'DeleteRequest', 'OtherRequest',
        'NonInternetUpload', 'NonInternetDownload', 'NonInternetDeleteFlow', 'NonInternetRoamUpload',
        'NonInternetRoamDownload',
        'NonInternetGetRequest', 'NonInternetHeadRequest', 'NonInternetPutRequest', 'NonInternetPostRequest',
        'NonInternetDeleteRequest', 'NonInternetOtherRequest', 'SpamRequest', 'PornReviewFalse', 'PornReviewTrue'
    ]

    def __init__(self, statistic, section, order):
        super().__init__()
        self.region_name = self.get_text(statistic, "Name")
        self.data = self.get_data_usage(section, self.GET_USAGE_KEYS)
        self.msg = self.format_message(statistic, order)

    def format_message(self, statistic, order):
        message_parts = [self.OBJ_TEMPLATE.format(
            order=order,
            region_name=self.region_name,
            **{key: self.data.get(key, '-') for key in self.GET_USAGE_KEYS}
        )]
        return ''.join(message_parts)

    def to_string(self):
        return self.msg


class GetUsageResult(Result):
    OBJ_TEMPLATE = (
            "Get Usage Result: \n"
            + " UserName: {UserName}, "
            + " BucketName: {BucketName}, "
            + " \n Region: {Region} "
    )

    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 = ""

        region = parseString(xml_response).documentElement.getElementsByTagName("Region")
        ii = 0
        for xml_statistic in region:
            Datas = xml_statistic.getElementsByTagName("Data")
            if Datas:
                ii = ii + 1
                for data in Datas:
                    statistic = GetUsageStatistics(xml_statistic, data, ii)
                    self.Regions.append(statistic)
                    region_list_msg += statistic.to_string()

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

    def get_xml_resp(self):
        return self.xmlResp

    def to_string(self):
        return self.msg
