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 GetAvailableBandwidthRequest(Request):

    def __init__(self, BeginDate=None, EndDate=None, Region=None, Freq=None, InOutType=None,
                 InternetType=None):
        self.BeginDate = BeginDate
        self.EndDate = EndDate
        self.Region = Region
        self.Freq = Freq
        self.InOutType = InOutType
        self.InternetType = InternetType

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

        if self.Region is not None:
            params['Region'] = self.Region
        if self.Freq is not None:
            params['Freq'] = self.Freq

        if self.InOutType is not None:
            params['InOutType'] = self.InOutType
        if self.InternetType is not None:
            params['InternetType'] = self.InternetType

        return params


class GetAvailableBandwidthStatistics(BaseStatistics):
    OBJ_TEMPLATE = (
            "\n    Get Available Bandwidth Statistics {order}: \n"
            + "       Date: {date}, "
            + "\n"
            + "       Data:  "
            + "       RegionName: {RegionName}, "
            + "       InternetInbound: {InternetInbound} "
            + "       NonInternetInbound: {NonInternetInbound} "
            + "       InternetOutbound: {InternetOutbound} "
            + "       NonInternetOutbound: {NonInternetOutbound} "
    )

    GET_AVAILABLE_BANDWIDTH_KEYS = [
        'RegionName', 'InternetInbound', 'NonInternetInbound', 'InternetOutbound', 'NonInternetOutbound'
    ]

    def __init__(self, statistic, section, order):
        super().__init__()
        self.date = self.get_text(statistic, "Date")
        self.data = self.get_data_usage(section, self.GET_AVAILABLE_BANDWIDTH_KEYS)
        self.msg = self.format_message(statistic, order)

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

    def to_string(self):
        return self.msg


class GetAvailableBandwidthResult(Result):
    OBJ_TEMPLATE = (
            "Get Available Bandwidth Result: \n"
            + " Account: {Account}, "
            + " UserName: {UserName}, "
            + " TimeZone: {TimeZone}, "
            + " Freq: {Freq} "
            + " InOutType: {InOutType} "
            + " InternetType: {InternetType} "
            + " \n Statistics: {Statistics} "
    )

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

    def get_header(self):
        return self.header

    def __init__(self):
        self.xmlResp = ""
        self.Account = None
        self.UserName = None
        self.TimeZone = None
        self.Freq = None
        self.InOutType = None
        self.InternetType = None
        self.statCnt = 0
        self.Statistics = []
        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.Account = result['Account']
        self.UserName = result['UserName']
        self.TimeZone = result['TimeZone']
        self.Freq = result['Freq']

        self.InOutType = result['InOutType']
        self.InternetType = result['InternetType']

        statistics_msg = ""

        statistics = parseString(xml_response).documentElement.getElementsByTagName("Statistics")
        ii = 0
        for xml_statistic in statistics:
            Datas = xml_statistic.getElementsByTagName("Data")
            if Datas:
                ii = ii + 1
                for data in Datas:
                    statistic = GetAvailableBandwidthStatistics(xml_statistic, data, ii)
                    self.Statistics.append(statistic)
                    statistics_msg += statistic.to_string()
        self.msg = self.OBJ_TEMPLATE.format(
            Account=self.Account,
            UserName=self.UserName,
            TimeZone=self.TimeZone,
            Freq=self.Freq,
            InOutType=self.InOutType,
            InternetType=self.InternetType,
            Statistics=statistics_msg,
        )

    def to_string(self):
        return self.msg

    def get_xml_resp(self):
        return self.xmlResp
