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


class GetBandwidthRequest(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": "GetBandwidth"}
        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 BandwidthData(object):
    OBJ_TEMPLATE = (
            "\n  Date {Date}"
            + "       UploadBW: {UploadBW}, "
            + "       DownloadBW:{DownloadBW} "
            + "       RoamUploadBW: {RoamUploadBW}, "
            + "       RoamDownloadBW:{RoamDownloadBW} "
            + "       NonInternetUploadBW: {NonInternetUploadBW}, "
            + "       NonInternetDownloadBW:{NonInternetDownloadBW} "
            + "       NonInternetRoamUploadBW: {NonInternetRoamUploadBW}, "
            + "       NonInternetRoamDownloadBW:{NonInternetRoamDownloadBW} "
    )

    def __init__(self, xml_data, idx):
        self.idx = idx
        self.Date = xml_data.getElementsByTagName("Date")[0].childNodes[0].data
        self.UploadBW = xml_data.getElementsByTagName("UploadBW")[0].childNodes[0].data
        self.DownloadBW = xml_data.getElementsByTagName("DownloadBW")[0].childNodes[0].data
        self.RoamUploadBW = xml_data.getElementsByTagName("RoamUploadBW")[0].childNodes[0].data
        self.RoamDownloadBW = xml_data.getElementsByTagName("RoamDownloadBW")[0].childNodes[0].data
        self.NonInternetUploadBW = xml_data.getElementsByTagName("NonInternetUploadBW")[0].childNodes[0].data
        self.NonInternetDownloadBW = xml_data.getElementsByTagName("NonInternetDownloadBW")[0].childNodes[0].data
        self.NonInternetRoamUploadBW = xml_data.getElementsByTagName("NonInternetRoamUploadBW")[0].childNodes[0].data
        self.NonInternetRoamDownloadBW = xml_data.getElementsByTagName("NonInternetRoamDownloadBW")[0].childNodes[
            0].data
        self.msg = self.OBJ_TEMPLATE.format(
            Date=self.Date, UploadBW=self.UploadBW, DownloadBW=self.DownloadBW, RoamUploadBW=self.RoamUploadBW,
            RoamDownloadBW=self.RoamDownloadBW,
            NonInternetUploadBW=self.NonInternetUploadBW, NonInternetDownloadBW=self.NonInternetDownloadBW,
            NonInternetRoamUploadBW=self.NonInternetRoamUploadBW,
            NonInternetRoamDownloadBW=self.NonInternetRoamDownloadBW
        )

    def to_string(self):
        return self.msg


class Region(object):
    OBJ_TEMPLATE = (
            "\n Region {order}:"
            + "       Name: {Name}, "
            + "       Data count:{Cnt} "
    )

    def __init__(self, region, order):
        self.Name = None
        self.Cnt = 0
        self.msg = ""
        self.dataList = []
        self.order = order
        self.Name = region.getElementsByTagName("Name")[0].childNodes[0].data
        data = region.getElementsByTagName("Data")
        idx = 0
        for xml_data in data:
            data = BandwidthData(xml_data, idx)
            self.dataList.append(data)
            idx = idx + 1
        self.Cnt = idx

        self.msg = self.OBJ_TEMPLATE.format(
            order=self.order,
            Name=self.Name,
            Cnt=self.Cnt,
        )

    def to_string(self):
        i = 0
        msg_str = self.msg
        while i < self.dataList.__len__():
            msg_str += self.dataList[i].to_string()
            i = i + 1
        return msg_str

    def get_data(self, index) -> BandwidthData or None:
        if (index < self.dataList.__len__()) & (index >= 0):
            return self.dataList[index]
        else:
            return None

    def get_data_cnt(self):
        return self.dataList.__len__()


class GetBandwidthResult(Result):
    OBJ_TEMPLATE = (
            "Get Bandwidth Result: \n"
            + " UserName: {UserName}, "
            + " RegionCount: {RegionCount} "
            + " \nRegions: {regionList_msg} "
    )

    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:
            one_region = Region(region, ii)
            self.Regions.append(one_region)
            ii = ii + 1
            region_list_msg += one_region.to_string()
        self.RegionCount = ii
        self.msg = self.OBJ_TEMPLATE.format(
            UserName=self.UserName,
            RegionCount=self.RegionCount,
            regionList_msg=region_list_msg
        )

    def get_xml_resp(self):
        return self.xmlResp

    def to_string(self):
        return self.msg

    def get_region(self, index) -> Region or None:
        if (index < self.Regions.__len__()) & (index >= 0):
            return self.Regions[index]
        else:
            return None
