import xml.sax
from ctyun.cloudtrail.model.result import ResponseHeader
from ctyun.util.utils import XMLHandler


class ServiceException(Exception):
    MSG_TEMPLATE = (
            'An error occurred: \n'
            + '  Response code: {Code}\n'
            + '  Error message: {Message}\n'
            + '  Resource: {Resource}\n'
            + '  Request id: {RequestId}'
    )
    msg = ""
    header = ResponseHeader()

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

    def get_header(self):
        return self.header

    def __init__(self, error_response):
        xh = XMLHandler()
        xml.sax.parseString(error_response, xh)
        err = xh.getDict()

        self.Code = err['Code']
        self.Message = err['Message']
        self.Resource = err['Resource']
        self.RequestId = err['RequestId']

        self.msg = self.MSG_TEMPLATE.format(
            Code=self.Code,
            Message=self.Message,
            Resource=self.Resource,
            RequestId=self.RequestId
        )
        super(ServiceException, self).__init__(self.msg)
        self.response = error_response

    def to_string(self):
        return self.msg
