import json
import datetime
import gitlab
import logging
from uncloud_pay.models import Product, Order, ProductToRecurringPeriod, Bill, Payment
from .models import VMMachine
import dns.zone
from dns.exception import DNSException
from django.conf import settings

log = logging.getLogger()

def finalize_order(request, customer, billing_address,
                    one_time_price, pricing_plan,
                    specs):
    product = Product.objects.first()
    recurring_period_product = ProductToRecurringPeriod.objects.filter(product=product, is_default=True).first()
    order = Order.objects.create(
            owner=request.user,
            customer=customer,
            billing_address=billing_address,
            one_time_price=one_time_price,
            pricing_plan=pricing_plan,
            recurring_period= recurring_period_product.recurring_period,
            product = product,
            config=json.dumps(specs)
        )
    if order:
        end_date = order.starting_date + datetime.timedelta(seconds=order.recurring_period.duration_seconds)
        bill = Bill.create_next_bill_for_order(order, ending_date=end_date)
        payment= Payment.withdraw(owner=request.user, amount=one_time_price, notes=f"BILL #{bill.id}")
        if payment:
            #Close the bill as the payment has been added
            VMMachine.create_instance(order)
            bill.close(status="paid")
    
    return order, bill

def add_to_dns_files(sub_domain, ipv4, ipv6, domain):
    gl = gitlab.Gitlab(settings.GITLAB_SERVER, oauth_token=settings.GITLAB_DNS_OAUTH_TOKEN)
    project = gl.projects.get(settings.GITLAB_DNS_PROJECT_ID)
    f_path = f'zones/{domain}'
    file = project.files.get(file_path=f_path, ref='master')
    if file:
        try:
            zone_file = file.decode()
            zone = dns.zone.from_file(zone_file, domain)

            log.info(f"Adding record on {zone.origin} of type A: {sub_domain}")

            rdataset = zone.find_rdataset(sub_domain, rdtype=dns.rdatatype.A, create=True)
            rdata = dns.rdtypes.IN.A.A(dns.rdataclass.IN, dns.rdatatype.A, address=ipv4)
            rdataset.add(rdata, ttl=600)
            
            log.info(f"Adding record on {zone.origin} of type AAAA: {sub_domain}")

            rdataset_ipv6 = zone.find_rdataset(sub_domain, rdtype=dns.rdatatype.AAAA, create=True)
            rdata_ipv6 = dns.rdtypes.IN.AAAA.AAAA(dns.rdataclass.IN, dns.rdatatype.AAAA, address=ipv6)
            rdataset_ipv6.add(rdata_ipv6, ttl=600)

            file.content = zone.to_text()
            
            # Write it back to gitlab
            file.save(branch='master', commit_message=f'Update ungleich-dns-zones {domain}')

        except DNSException as e:
            log.error(e.__class__, e)
            raise e

def remove_from_dns_files(sub_domain, domain):
    gl = gitlab.Gitlab(settings.GITLAB_SERVER, oauth_token=settings.GITLAB_DNS_OAUTH_TOKEN)
    project = gl.projects.get(settings.GITLAB_DNS_PROJECT_ID)
    f_path = f'zones/{domain}'
    file = project.files.get(file_path=f_path, ref='master')
    if file:
        try:
            zone_file = file.decode()
            zone = dns.zone.from_file(zone_file, domain)

            log.info(f"Removing record on {zone.origin}: {sub_domain}")
            zone.delete_node(sub_domain)

            file.content = zone.to_text()
            # Write it back to gitlab
            file.save(branch='master', commit_message=f'Removing {sub_domain} from {domain}')
        except DNSException as e:
            log.error(e.__class__, e)
            raise e