import CloudFlare


class DnsRecord:
    def __init__(self, name, record_type, content):
        self.name = name
        self.record_type = record_type
        self.content = content

    def __iter__(self):
        yield 'name', self.name
        yield 'type', self.record_type
        yield 'content', self.content


class MxRecord:
    def __init__(self, name, content, priority):
        self.name = name
        self.record_type = "MX"
        self.content = content
        self.priority = priority

    def __iter__(self):
        yield 'name', self.name
        yield 'type', self.record_type
        yield 'content', self.content
        yield 'priority', self.priority


class SrvData:
    def __init__(self, service, proto, name, priority, weight, port, target):
        self.service = service
        self.proto = proto
        self.name = name
        self.priority = priority
        self.weight = weight
        self.port = port
        self.target = target

    def __iter__(self):
        yield 'service', self.service
        yield 'proto', self.proto
        yield 'name', self.name
        yield 'priority', self.priority
        yield 'weight', self.weight
        yield 'port', self.port
        yield 'target', self.target


class SrvRecord:
    type = "SRV"

    # srv_data = SrvData
    def __init__(self, srv_data: SrvData):
        self.srv_data = srv_data

    def __iter__(self):
        yield 'type', self.type
        yield 'data', dict(self.srv_data)


def get_zone_dns(cf: CloudFlare.CloudFlare, zone_id: str) -> list:
    # request the DNS records from that zone
    try:
        dns_records = cf.zones.dns_records.get(zone_id)
    except CloudFlare.exceptions.CloudFlareAPIError as e:
        exit('/zones/dns_records.get %d %s - api call failed' % (e, e))

    record_list = []
    # then all the DNS records for that zone
    for dns_record in dns_records:
        list_record = DnsRecord(name=dns_record['name'], record_type=dns_record['type'], content=dns_record['content'])
        record_list.append(dict(list_record))
        # r_id = dns_record['id']
    return record_list


def post_dns_records(cf: CloudFlare.CloudFlare, zone_id: str, records: list[SrvRecord, DnsRecord]):
    existing_records = get_zone_dns(cf, zone_id)
    for record in records:
        # TODO this should check if record already exists and add if not
        record_dict = dict(record)
        try:
            cf.zones.dns_records.post(zone_id, data=dict(record))
        except CloudFlare.exceptions.CloudFlareAPIError as e:
            print('/zones/dns_records.get %d %s - api call failed' % (e, e))
