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

    def __init__(self, BeginDate=None, EndDate=None, Bucket=None, Region=None, Freq=None, StorageClass=None):
        self.BeginDate = BeginDate
        self.EndDate = EndDate
        self.Bucket = Bucket
        self.Region = Region
        self.Freq = Freq
        self.StorageClass = StorageClass

    def get_params(self):
        params = {"Action": "GetCapacity"}
        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['Bucket'] = self.Bucket
        if self.Region is not None:
            params['Region'] = self.Region
        if self.Freq is not None:
            params['Freq'] = self.Freq
        if self.StorageClass is not None:
            params['StorageClass'] = self.StorageClass
        return params


class CapacityStatistics(BaseStatistics):
    OBJ_TEMPLATE = (
        "\n    Capacity Statistic {order}: \n"
        "       Date: {date} \n"
        "       {storage_class} Data:  \n"
        "       MaxCapacity: {MaxCapacity} "
        "       AverageCapacity: {AverageCapacity} "
        "       SampleCapacity: {SampleCapacity} \n"
    )

    CAPACITY_KEYS = ["MaxCapacity", "AverageCapacity", "SampleCapacity"]

    def __init__(self, statistic, order):
        super().__init__()
        self.date = self.get_text(statistic, "Date")
        self.storage_class = self.get_response_storage(statistic)
        self.standard_data = self.get_data(statistic, "Data", self.CAPACITY_KEYS)
        self.standard_ia_data = self.get_data(statistic, "Standard_ia", self.CAPACITY_KEYS)
        self.msg = self.format_message(statistic, order)

    def format_message(self, statistic, order):
        storage_classes = {
            "ALL": ["Standard", "StandardIA"],
            "STANDARD": ["Standard"],
            "STANDARD_IA": ["StandardIA"]
        }
        message_parts = []
        for storage_class in storage_classes.get(self.storage_class):
            message_parts.append(self.OBJ_TEMPLATE.format(
                order=order,
                date=self.date,
                storage_class=storage_class,
                **self.select_data(storage_class, self.standard_data, self.standard_ia_data, self.CAPACITY_KEYS)
            ))
        return ''.join(message_parts)

    def to_string(self):
        return self.msg


class GetCapacityResult(Result):
    OBJ_TEMPLATE = (
            "Get Capacity Result: \n"
            + " Account: {Account}, "
            + " UserName: {UserName}, "
            + " TimeZone: {TimeZone}, "
            + " Freq: {Freq} "
            + " StorageClass: {StorageClass} "
            + " BucketName: {BucketName} "
            + " RegionName: {RegionName} "
            + " \n Statistics: {Statistics} "
    )

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

    def get_header(self):
        return self.header

    def __init__(self):
        self.Account = None
        self.UserName = None
        self.TimeZone = None
        self.Freq = None
        self.StorageClass = None
        self.BucketName = None
        self.RegionName = None
        self.Statistics = []
        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.Account = result['Account']
        self.UserName = result['UserName']
        self.TimeZone = result['TimeZone']
        self.Freq = result['Freq']
        self.StorageClass = result['StorageClass']
        self.BucketName = result['BucketName']
        self.RegionName = result['RegionName']

        statistics_msg = ""

        statistics = parseString(xml_response).documentElement.getElementsByTagName("Statistics")
        ii = 0
        for xml_statistic in statistics:
            ii = ii + 1
            statistic = CapacityStatistics(xml_statistic, 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,
            StorageClass=self.StorageClass,
            BucketName=self.BucketName,
            RegionName=self.RegionName,
            Statistics=statistics_msg,
        )

    def to_string(self):
        return self.msg

    def get_xml_resp(self):
        return self.xmlResp
