class Balance(Base):
    def __init__(self):
        self.amount = None
        self.type = None
        self.payment = None class Call(Base):

    def __init__(self):
        self.id = None
        self._data = None

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, value):
        self._data = CallData().load(value[0])

    def __str__(self):
        return "\n".join([
            'id                 : %s' % self.id,
            'data.' + 'data.'.join(str(self._data).splitlines(True)),
        ]) class CallList(BaseList):
    def __init__(self):
        # We're expecting items of type CallData
        super(CallList, self).__init__(CallData)
        self.perPage = None
        self.currentPage = None
        self.pageCount = None
        self._pagination = None

    @property
    def data(self):
        return self.items

    @property
    def pagination(self):
        return {
            "totalCount": self.totalCount,
            "pageCount": self.pageCount,
            "currentPage": self.currentPage,
            "perPage": self.perPage
        }

    @pagination.setter
    def pagination(self, value):
        if isinstance(value, dict):
            self.totalCount = value['totalCount']
            self.pageCount = value['pageCount']
            self.currentPage = value['currentPage']
            self.perPage = value['perPage']
            self.limit = self.perPage * self.currentPage
            self.offset = self.perPage * (self.currentPage - 1)

    @data.setter
    def data(self, value):
        if isinstance(value, list):
            self.count = len(value)
            self.items = value class Contact(Base):

    def __init__(self):
        self.id = None
        self.href = None
        self.msisdn = None
        self.firstName = None
        self.lastName = None
        self._customDetails = None
        self._groups = None
        self._messages = None
        self._createdDatetime = None
        self._updatedDatetime = None

    @property
    def customDetails(self):
        return self._customDetails

    @customDetails.setter
    def customDetails(self, value):
        self._customDetails = CustomDetails().load(value)

    @property
    def groups(self):
        return self._groups

    @groups.setter
    def groups(self, value):
        self._groups = GroupReference().load(value)

    @property
    def messages(self):
        return self._messages

    @messages.setter
    def messages(self, value):
        self._messages = MessageReference().load(value)

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value)

    @property
    def updatedDatetime(self):
        return self._updatedDatetime

    @updatedDatetime.setter
    def updatedDatetime(self, value):
        self._updatedDatetime = self.value_to_time(value) class ContactList(BaseList):

    def __init__(self):
        # Signal the BaseList that we're expecting items of type Contact...
        super(ContactList, self).__init__(Contact) class Error(Base):
    def __init__(self):
        self.code = None
        self.description = None
        self.parameter = None

    def __str__(self):
        return str(dict(code=self.code, description=self.description, parameter=self.parameter)) class ValidationError(ValueError):
    """Exception raised for errors in validation.

    Attributes:
        message -- explanation of the error
    """

    def __init__(self, message):
        self.message = message class Group(Base):

    def __init__(self):
        self.id = None
        self.href = None
        self.name = None
        self._contacts = None
        self.createdDatetime = None
        self.updatedDatetime = None

    @property
    def contacts(self):
        return self._contacts

    @contacts.setter
    def contacts(self, value):
        self._contacts = ContactReference().load(value)

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value)

    @property
    def updatedDatetime(self):
        return self._updatedDatetime

    @updatedDatetime.setter
    def updatedDatetime(self, value):
        self._updatedDatetime = self.value_to_time(value) class GroupList(BaseList):

    def __init__(self):
        # Signal the BaseList that we're expecting items of type Group...
        super(GroupList, self).__init__(Group) class HLR(Base):
    def __init__(self):
        self.id = None
        self.href = None
        self.msisdn = None
        self.network = None
        self.reference = None
        self.status = None
        self.details = None
        self._createdDatetime = None
        self._statusDatetime = None

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value)

    @property
    def statusDatetime(self):
        return self._statusDatetime

    @statusDatetime.setter
    def statusDatetime(self, value):
        self._statusDatetime = self.value_to_time(value) class Message(Base):
    def __init__(self):
        self.id = None
        self.href = None
        self.direction = None
        self.type = None
        self.originator = None
        self.body = None
        self.reference = None
        self.validity = None
        self.gateway = None
        self.typeDetails = None
        self.datacoding = None
        self.mclass = None
        self._scheduledDatetime = None
        self._createdDatetime = None
        self._recipients = None

    @property
    def scheduledDatetime(self):
        return self._scheduledDatetime

    @scheduledDatetime.setter
    def scheduledDatetime(self, value):
        self._scheduledDatetime = self.value_to_time(value)

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value)

    @property
    def recipients(self):
        return self._recipients

    @recipients.setter
    def recipients(self, value):
        value['items'] = [Recipient().load(r) for r in value['items']]
        self._recipients = value class MessageList(BaseList):
    def __init__(self):
        # We're expecting items of type Message
        super(MessageList, self).__init__(Message) class MMS(Base):
    def __init__(self):
        self.id = None
        self.href = None
        self.direction = None
        self.originator = None
        self.subject = None
        self.body = None
        self.mediaUrls = None
        self.reference = None
        self._scheduledDatetime = None
        self._createdDatetime = None
        self._recipients = None

    @property
    def scheduledDatetime(self):
        return self._scheduledDatetime

    @scheduledDatetime.setter
    def scheduledDatetime(self, value):
        self._scheduledDatetime = self.value_to_time(value)

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value)

    @property
    def recipients(self):
        return self._recipients

    @recipients.setter
    def recipients(self, value):
        value['items'] = [Recipient().load(r) for r in value['items']]
        self._recipients = value

    def __str__(self):
        return "\n".join([
            "id                      : %s" % self.id,
            "href                    : %s" % self.href,
            "direction               : %s" % self.direction,
            "originator              : %s" % self.originator,
            "subject                 : %s" % self.subject,
            "body                    : %s" % self.body,
            "mediaUrls               : %s" % ",".join(self.mediaUrls),
            "reference               : %s" % self.reference,
            "scheduledDatetime       : %s" % self.scheduledDatetime,
            "createdDatetime         : %s" % self.createdDatetime,
            "recipients              : %s" % self.recipients,
        ]) class VoiceWebhook(Base):
    def __init__(self):
        self.id = None
        self.url = None
        self.token = None
        self._createdAtDatetime = None
        self._updatedAtDatetime = None
        self._links = None

    @property
    def createdAtDatetime(self):
        return self._createdAtDatetime

    @createdAtDatetime.setter
    def createdAt(self, value):
        if value is not None:
            self._createdAtDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    @property
    def updatedAtDatetime(self):
        return self._updatedAtDatetime

    @updatedAtDatetime.setter
    def updatedAt(self, value):
        if value is not None:
            self._updatedAtDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    def load(self, data):
        if data.get('data') is not None:
            items = data.get('data')[0].items()
        else:
            items = list(data.items())

        for name, value in items:
            if hasattr(self, name) and not callable(getattr(self, name)):
                setattr(self, name, value)

        return self

    def __str__(self):
        return "\n".join([
            'webhook id         : %s' % self.id,
            'url                : %s' % self.url,
            'token              : %s' % self.token,
            'createdAtDatetime  : %s' % self._createdAtDatetime,
            'updatedAtDatetime  : %s' % self._updatedAtDatetime,
            'links              : %s' % self._links
        ]) class VoiceWebhookList(Base):
    def __init__(self):
        self._items = None

    @property
    def data(self):
        return self._items

    @data.setter
    def data(self, value):
        if isinstance(value, list):
            self._items = []
            for item in value:
                self._items.append(VoiceWebhook().load(item))

    def __str__(self):
        item_ids = []
        if self._items is not None:
            for voice_item in self._items:
                item_ids.append(voice_item.id)

        return "\n".join([
            'items IDs  : %s' % item_ids,
            'count      : %s' % len(item_ids)
        ]) class VoiceMessagesList(BaseList):
    def __init__(self):
        super(VoiceMessagesList, self).__init__(VoiceMessage)
        self.perPage = None
        self.currentPage = None
        self.pageCount = None
        self._pagination = None

    @property
    def data(self):
        return self.items

    @property
    def pagination(self):
        return {
            "totalCount": self.totalCount,
            "pageCount": self.pageCount,
            "currentPage": self.currentPage,
            "perPage": self.perPage
        }

    @pagination.setter
    def pagination(self, value):
        if isinstance(value, dict):
            self.totalCount = value['totalCount']
            self.pageCount = value['pageCount']
            self.currentPage = value['currentPage']
            self.perPage = value['perPage']
            self.limit = self.perPage * self.currentPage
            self.offset = self.perPage * (self.currentPage - 1)

    @data.setter
    def data(self, value):
        if isinstance(value, list):
            self.count = len(value)
            self.items = value class VoiceMessage(Base):
    def __init__(self):
        self.id = None
        self.href = None
        self.originator = None
        self.body = None
        self.reference = None
        self.language = None
        self.voice = None
        self.repeat = None
        self.ifMachine = None
        self._scheduledDatetime = None
        self._createdDatetime = None
        self._recipients = None

    @property
    def scheduledDatetime(self):
        return self._scheduledDatetime

    @scheduledDatetime.setter
    def scheduledDatetime(self, value):
        self._scheduledDatetime = self.value_to_time(value)

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value)

    @property
    def recipients(self):
        return self._recipients

    @recipients.setter
    def recipients(self, value):
        value['items'] = [Recipient().load(r) for r in value['items']]
        self._recipients = value class Lookup(Base):
    def __init__(self):
        self.href = None
        self.countryCode = None
        self.countryPrefix = None
        self.phoneNumber = None
        self.type = None
        self._formats = None
        self._hlr = None

    def __str__(self):
        return str(self.__class__) + ": " + str(self.__dict__)

    @property
    def formats(self):
        return self._formats

    @formats.setter
    def formats(self, value):
        self._formats = Formats().load(value)

    @property
    def hlr(self):
        return self._hlr

    @hlr.setter
    def hlr(self, value):
        self._hlr = HLR().load(value) class Verify(Base):
    def __init__(self):
        self.id = None
        self.href = None
        self.recipient = None
        self.reference = None
        self.messages = None
        self.status = None
        self._createdDatetime = None
        self._validUntilDatetime = None

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value)

    @property
    def validUntilDatetime(self):
        return self._validUntilDatetime

    @validUntilDatetime.setter
    def validUntilDatetime(self, value):
        self._validUntilDatetime = self.value_to_time(value) class HttpClient:
    """Used for sending simple HTTP requests."""

    def __init__(self, endpoint, access_key, user_agent):
        self.__supported_status_codes = [200, 201, 204, 401, 404, 405, 422]

        self.endpoint = endpoint
        self.access_key = access_key
        self.user_agent = user_agent

    def request(self, path, method='GET', params=None, format=ResponseFormat.text):
        """Builds a request and gets a response."""
        if params is None:
            params = {}
        url = urljoin(self.endpoint, path)
        headers = {
            'Accept': 'application/json',
            'Authorization': 'AccessKey ' + self.access_key,
            'User-Agent': self.user_agent,
            'Content-Type': 'application/json; charset=UTF-8'
        }

        method_switcher = {
            'DELETE': lambda: requests.delete(url, verify=True, headers=headers, data=json_serialize(params)),
            'GET': lambda: requests.get(url, verify=True, headers=headers, params=params),
            'PATCH': lambda: requests.patch(url, verify=True, headers=headers, data=json_serialize(params)),
            'POST': lambda: requests.post(url, verify=True, headers=headers, data=json_serialize(params)),
            'PUT': lambda: requests.put(url, verify=True, headers=headers, data=json_serialize(params))
        }
        if method not in method_switcher:
            raise ValueError(str(method) + ' is not a supported HTTP method')

        response = method_switcher[method]()

        if response.status_code not in self.__supported_status_codes:
            response.raise_for_status()

        response_switcher = {
            ResponseFormat.text: response.text,
            ResponseFormat.binary: response.content
        }
        return response_switcher.get(format) class ResponseFormat(Enum):
    text = 1
    binary = 2 class ConversationMessage(Base):

    def __init__(self):
        self.id = None
        self.conversationId = None
        self.channelId = None
        self.direction = None
        self.status = None
        self.type = None
        self.content = None
        self._createdDatetime = None
        self._updatedDatetime = None

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        if value is not None:
            self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    @property
    def updatedDatetime(self):
        return self._updatedDatetime

    @updatedDatetime.setter
    def updatedDatetime(self, value):
        if value is not None:
            self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    def __str__(self):
        return "\n".join([
            'message id        : %s' % self.id,
            'channel id        : %s' % self.channelId,
            'direction         : %s' % self.direction,
            'status            : %s' % self.status,
            'type              : %s' % self.type,
            'content           : %s' % self.content,
            'created date time : %s' % self._createdDatetime,
            'updated date time : %s' % self._updatedDatetime
        ]) class ConversationMessageList(Base):

    def __init__(self):
        self.offset = None
        self.limit = None
        self.count = None
        self.totalCount = None
        self._items = None

    @property
    def items(self):
        return self._items

    @items.setter
    def items(self, value):
        items = []
        if isinstance(value, list):
            for item in value:
                items.append(ConversationMessage().load(item))

        self._items = items

    def __str__(self):
        item_ids = []
        for msg_item in self._items:
            item_ids.append(msg_item.id)

        return "\n".join([
            'items IDs  : %s' % item_ids,
            'offset     : %s' % self.offset,
            'limit      : %s' % self.limit,
            'count      : %s' % self.count,
            'totalCount : %s' % self.totalCount,
        ]) class Conversation(Base):

    def __init__(self):
        self.id = None
        self.contactId = None
        self._contact = None
        self.lastUsedChannelId = None
        self._channels = None
        self._messages = None
        self.status = None
        self._createdDatetime = None
        self._updatedDatetime = None
        self._lastReceivedDatetime = None

    @property
    def contact(self):
        return self._contact

    @contact.setter
    def contact(self, value):
        self._contact = ConversationContact().load(value)

    @property
    def messages(self):
        return self._messages

    @messages.setter
    def messages(self, value):
        self._messages = ConversationMessageReference().load(value)

    @property
    def channels(self):
        return self._channels

    @channels.setter
    def channels(self, value):
        if isinstance(value, list):
            self._channels = []
            for channelData in value:
                self._channels.append(Channel().load(channelData))
        else:
            self._channels = value

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    @property
    def updatedDatetime(self):
        return self._updatedDatetime

    @updatedDatetime.setter
    def updatedDatetime(self, value):
        self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    @property
    def lastReceivedDatetime(self):
        return self._lastReceivedDatetime

    @lastReceivedDatetime.setter
    def lastReceivedDatetime(self, value):
        self._lastReceivedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    def __str__(self):
        return "\n".join([
            'id                   : %s' % self.id,
            'contact id           : %s' % self.contactId,
            'last used channel id : %s' % self.lastUsedChannelId,
            'message id           : %s' % self.messages.lastMessageId,
            'message total count  : %s' % self.messages.totalCount,
            'status               : %s' % self.status,
            'created date time    : %s' % self.createdDatetime,
            'updated date time    : %s' % self.updatedDatetime,
            'last received date   : %s' % self.lastReceivedDatetime,
        ]) class ConversationList(Base):
    def __init__(self):
        self.offset = None
        self.limit = None
        self.count = None
        self.totalCount = None
        self._items = None

    @property
    def items(self):
        return self._items

    @items.setter
    def items(self, value):
        if isinstance(value, list):
            self._items = []
            for item in value:
                self._items.append(Conversation().load(item))

    def __str__(self):
        item_ids = []
        for msg_item in self._items:
            item_ids.append(msg_item.id)

        return "\n".join([
            'items IDs  : %s' % item_ids,
            'offset     : %s' % self.offset,
            'limit      : %s' % self.limit,
            'count      : %s' % self.count,
            'totalCount : %s' % self.totalCount,
        ]) class ConversationWebhook(Base):

    def __init__(self):
        self.id = None
        self.channelId = None
        self.url = None
        self.events = None
        self.status = None
        self._createdDatetime = None
        self._updatedDatetime = None

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdDatetime(self, value):
        self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    @property
    def updatedDatetime(self):
        return self._updatedDatetime

    @updatedDatetime.setter
    def updatedDatetime(self, value):
        self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    def __str__(self):
        return "\n".join([
            'id                : %s' % self.id,
            'events            : %s' % self.events,
            'channel id        : %s' % self.channelId,
            'status            : %s' % self.status,
            'url               : %s' % self.url,
            'created date time : %s' % self.createdDatetime,
            'updated date time : %s' % self.updatedDatetime
        ]) class ConversationWebhookList(Base):
    def __init__(self):
        self.offset = None
        self.limit = None
        self.count = None
        self.totalCount = None
        self._items = None

    @property
    def items(self):
        return self._items

    @items.setter
    def items(self, value):
        items = []
        if isinstance(value, list):
            for item in value:
                items.append(ConversationWebhook().load(item))

        self._items = items

    def __str__(self):
        item_ids = []
        for item in self._items:
            item_ids.append(item.id)

        return "\n".join([
            'items IDs  : %s' % item_ids,
            'offset     : %s' % self.offset,
            'limit      : %s' % self.limit,
            'count      : %s' % self.count,
            'totalCount : %s' % self.totalCount,
        ]) class VoiceRecordingsList(Base):
    def __init__(self):
        self._items = None

    @property
    def data(self):
        return self._items

    @data.setter
    def data(self, value):
        if isinstance(value, list):
            self._items = []
            for item in value:
                self._items.append(VoiceRecording().load(item))

    def __str__(self):
        item_ids = []
        if self._items is not None:
            for recording_item in self._items:
                item_ids.append(recording_item.id)

        return "\n".join([
            'items IDs  : %s' % item_ids,
            'count      : %s' % len(item_ids)
        ]) class VoiceRecording(Base):

    def __init__(self):
        self.id = None
        self.format = None
        self.type = None
        self.legId = None
        self.status = None
        self.duration = None
        self._createdDatetime = None
        self._updatedDatetime = None
        self._links = None

    @property
    def createdDatetime(self):
        return self._createdDatetime

    @createdDatetime.setter
    def createdAt(self, value):
        if value is not None:
            self._createdDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    @property
    def updatedDatetime(self):
        return self._updatedDatetime

    @updatedDatetime.setter
    def updatedAt(self, value):
        if value is not None:
            self._updatedDatetime = self.value_to_time(value, '%Y-%m-%dT%H:%M:%SZ')

    def __str__(self):
        return "\n".join([
            'recording id           : %s' % self.id,
            'format            : %s' % self.format,
            'type              : %s' % self.type,
            'leg id            : %s' % self.legId,
            'status            : %s' % self.status,
            'duration          : %s' % self.duration,
            'created date time : %s' % self._createdDatetime,
            'updated date time : %s' % self._updatedDatetime,
            'links             : %s' % self._links
        ]) class VoiceTranscriptionsList(BaseList):
    def __init__(self):
        super(VoiceTranscriptionsList, self).__init__(VoiceTranscriptionData)
        self.perPage = None
        self.currentPage = None
        self.pageCount = None
        self._pagination = None

    @property
    def data(self):
        return self.items

    @property
    def pagination(self):
        return {
            "totalCount": self.totalCount,
            "pageCount": self.pageCount,
            "currentPage": self.currentPage,
            "perPage": self.perPage
        }

    @pagination.setter
    def pagination(self, value):
        if isinstance(value, dict):
            self.totalCount = value['totalCount']
            self.pageCount = value['pageCount']
            self.currentPage = value['currentPage']
            self.perPage = value['perPage']
            self.limit = self.perPage * self.currentPage
            self.offset = self.perPage * (self.currentPage - 1)

    @data.setter
    def data(self, value):
        if isinstance(value, list):
            self.count = len(value)
            self.items = value class VoiceTranscriptionsView(BaseList):
    def __init__(self):
        super(VoiceTranscriptionsView, self).__init__(VoiceTranscriptionData)

    @property
    def data(self):
        return self.items

    @data.setter
    def data(self, value):
        if isinstance(value, list):
            self.items = value class CallFlow(Base):

    def __init__(self):
        self.id = None
        self.title = None
        self.record = None
        self.steps = None
        self.default = None
        self._createdAt = None
        self._updatedAt = None

    @property
    def createdAt(self):
        return self._createdAt

    @createdAt.setter
    def createdAt(self, value):
        self._createdAt = self.value_to_time(value)

    @property
    def updatedAt(self):
        return self._updatedAt

    @updatedAt.setter
    def updatedAt(self, value):
        self._updatedAt = self.value_to_time(value)

    def load(self, data):
        if data.get('data') is not None:
            items = data.get('data')[0].items()
        else:
            items = list(data.items())

        for name, value in items:
            if hasattr(self, name) and not callable(getattr(self, name)):
                setattr(self, name, value)

        return self class CallFlowList(BaseList):

    def __init__(self):
        self._data = None
        self._pagination = None

        super(CallFlowList, self).__init__(CallFlow)

    @property
    def data(self):
        return self._data

    @property
    def pagination(self):
        return self._pagination

    @pagination.setter
    def pagination(self, value):
        self._pagination = value

    @data.setter
    def data(self, value):
        """Create typed objects from the dicts."""
        items = []
        for item in value:
            items.append(self.itemType().load(item))

        self._data = items class CallFlowNumberList(BaseList):
    def __init__(self):
        self._data = None
        self._pagination = None

        super(CallFlowNumberList, self).__init__(CallFlowNumber)

    @property
    def data(self):
        return self._data

    @property
    def pagination(self):
        return self._pagination

    @pagination.setter
    def pagination(self, value):
        self._pagination = value

    @data.setter
    def data(self, value):
        """Create typed objects from the dicts."""
        items = []
        for item in value:
            items.append(self.itemType().load(item))

        self._data = items class Number(Base):
    def __init__(self):
        self.number = None
        self.country = None
        self.region = None
        self.locality = None
        self.features = None
        self.tags = None
        self.type = None
        self.status = None class NumberList(BaseList):
    def __init__(self):
        # We're expecting items of type Number
        super(NumberList, self).__init__(Number)
import sys
import json
import io
from messagebird.balance import Balance
from messagebird.call import Call
from messagebird.call_list import CallList
from messagebird.contact import Contact, ContactList
from messagebird.error import Error, ValidationError
from messagebird.group import Group, GroupList
from messagebird.hlr import HLR
from messagebird.message import Message, MessageList
from messagebird.mms import MMS
from messagebird.voice_webhook import VoiceWebhook, VoiceWebhookList
from messagebird.voicemessage import VoiceMessagesList, VoiceMessage
from messagebird.lookup import Lookup
from messagebird.verify import Verify
from messagebird.http_client import HttpClient, ResponseFormat
from messagebird.conversation_message import ConversationMessage, ConversationMessageList
from messagebird.conversation import Conversation, ConversationList
from messagebird.conversation_webhook import ConversationWebhook, ConversationWebhookList
from messagebird.voice_recording import VoiceRecordingsList, VoiceRecording
from messagebird.voice_transcription import VoiceTranscriptionsList, VoiceTranscriptionsView
from messagebird.call_flow import CallFlow, CallFlowList, CallFlowNumberList
from messagebird.number import Number, NumberList
        uri = CONVERSATION_PATH + '/' + str(conversation_id) + '/' + CONVERSATION_MESSAGES_PATH
        return ConversationMessage().load(self.request(uri, 'POST', message_create_request, CONVERSATION_TYPE))

    def conversation_read_message(self, message_id):
        uri = CONVERSATION_MESSAGES_PATH + '/' + str(message_id)
        return ConversationMessage().load(self.request(uri, 'GET', None, CONVERSATION_TYPE))

    def conversation_create_webhook(self, webhook_create_request):
        return ConversationWebhook().load(
            self.request(CONVERSATION_WEB_HOOKS_PATH, 'POST', webhook_create_request, CONVERSATION_TYPE))

    def conversation_update_webhook(self, id, update_request):
        """
        Updates a webhook with the supplied parameters.

        API Reference: https://developers.messagebird.com/api/conversations/#webhooks
        """
        uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id)
        web_hook = self.request(uri, 'PATCH', update_request, CONVERSATION_TYPE)
        return ConversationWebhook().load(web_hook)

    def conversation_delete_webhook(self, id):
        uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id)
        self.request(uri, 'DELETE', None, CONVERSATION_TYPE)

    def conversation_list_webhooks(self, limit=10, offset=0):
        uri = CONVERSATION_WEB_HOOKS_PATH + '?' + self._format_query(limit, offset)

        return ConversationWebhookList().load(self.request(uri, 'GET', None, CONVERSATION_TYPE))

    def conversation_read_webhook(self, id):
        uri = CONVERSATION_WEB_HOOKS_PATH + '/' + str(id)
        return ConversationWebhook().load(self.request(uri, 'GET', None, CONVERSATION_TYPE))

    def voice_recording_list_recordings(self, call_id, leg_id):
        uri = self.generate_voice_calls_url(call_id=call_id, leg_id=leg_id)
        return VoiceRecordingsList().load(self.request(uri, 'GET'))

    def voice_transcription_list(self, call_id, leg_id, recording_id):
        """List voice transcriptions."""
        uri = self.generate_voice_calls_url(call_id, leg_id, recording_id)
        return VoiceTranscriptionsList().load(self.request(uri, 'GET'))

    def voice_transcription_download(self, call_id, leg_id, recording_id, transcriptions_file):
        """Download voice transcription file."""
        uri = self.generate_voice_calls_url(call_id, leg_id, recording_id) + '/' + str(transcriptions_file)
        return self.request(uri, 'GET')

    def voice_transcription_view(self, call_id, leg_id, recording_id, transcriptions_id):
        """Get voice transcription data."""
        uri = self.generate_voice_calls_url(call_id, leg_id, recording_id) + '/' + str(transcriptions_id)
        return VoiceTranscriptionsView().load(self.request(uri, 'GET'))

    def voice_transcription_create(self, call_id, leg_id, recording_id, language):
        """Create a voice transcription."""
        uri = self.generate_voice_calls_url(call_id, leg_id, recording_id)
        params = {'language': str(language)}
        return VoiceTranscriptionsView().load(self.request(uri, 'POST', params, VOICE_TYPE))

    def voice_recording_view(self, call_id, leg_id, recording_id):
        uri = self.generate_voice_calls_url(call_id=call_id, leg_id=leg_id) + '/' + str(recording_id)
        recording_response = self.request(uri, 'GET')
        recording_links = recording_response.get('_links')
        if recording_links is not None:
            recording_response['data'][0]['_links'] = recording_links
        return VoiceRecording().load(recording_response['data'][0])

    def voice_recording_delete(self, call_id, leg_id, recording_id):
        uri = self.generate_voice_calls_url(call_id=call_id, leg_id=leg_id) + '/' + str(recording_id)
        recording_response = self.request(uri, 'DELETE', None, VOICE_TYPE)

    def voice_recording_download(self, call_id, leg_id, recording_id):
        uri = self.generate_voice_calls_url(call_id=call_id, leg_id=leg_id) + '/' + str(recording_id)
        recording_response = self.request(uri, 'GET')
        recording_links = recording_response.get('_links')
        if recording_links is None or recording_links.get('file') is None:
            raise (ErrorException('There is no recording available'))
        recording_file = recording_links.get('file')
        recording_file = self.request_store_as_file(VOICE_API_ROOT + recording_file, recording_id + '.wav')
        return VOICE_API_ROOT + recording_file

    def voice_read_webhook(self, id):
        """
        Retrieve a voice webhook
        API Reference: https://developers.messagebird.com/api/voice-calling/#webhooks
        """
        uri = VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH + '/' + str(id)
        return VoiceWebhook().load(self.request(uri, 'GET', None, VOICE_TYPE))

    def voice_list_webhooks(self, limit=10, offset=0):
        """ Retrieve a list of voice webhooks. """
        uri = VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH + '?' + self._format_query(limit, offset)
        return VoiceWebhookList().load(self.request(uri, 'GET', None, VOICE_TYPE))

    def voice_create_webhook(self, create_webhook_request):
        """ Create a voice webhook. """
        if create_webhook_request is None:
            raise ValidationError('Create request is empty')

        uri = VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH
        return VoiceWebhook().load(self.request(uri, 'POST', create_webhook_request.__dict__(), VOICE_TYPE))

    def voice_update_webhook(self, id, update_webhook_request):
        """ Update a voice webhook. """
        if update_webhook_request is None:
            raise ValidationError('Update request is empty')

        uri = VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH + '/' + str(id)
        return VoiceWebhook().load(self.request(uri, 'PUT', update_webhook_request.__dict__(), VOICE_TYPE))

    def voice_delete_webhook(self, id):
        """ Delete a voice webhook. """
        uri = VOICE_API_ROOT + '/' + VOICE_WEB_HOOKS_PATH + '/' + str(id)
        self.request(uri, 'DELETE', None, VOICE_TYPE)

    def call_flow(self, id):
        return CallFlow().load(self.request('call-flows/' + str(id), 'GET', None, VOICE_TYPE))

    def call_flow_list(self, limit=10, offset=0):
        query = self._format_query(limit, offset)

        return CallFlowList().load(self.request('call-flows?' + query, 'GET', None, VOICE_TYPE))