import json
from matrixhosting.models import VMInstance
from uncloud_pay.models import Order
from django.db.models.signals import post_save
from django.dispatch import receiver

@receiver(post_save, sender=Order)
def create_instance(sender, instance, created, **kwargs):
    if not created:
        return
    machine = VMInstance.objects.filter(order=instance).first()
    if not machine:
        order_config = json.loads(instance.config)
        instance_config = {'cpuCores': order_config['cores'], 'ram': order_config['memory'], 'storage': order_config['storage'], 
                            'matrixDomain': order_config['matrix_domain'], 'homeserverDomain': order_config['homeserver_domain'], 
                            'webClientDomain': order_config['webclient_domain'], 'isOpenRegistration': order_config['is_open_registration']}
        VMInstance.objects.create(owner=instance.owner, order=instance, vm_name=order_config['homeserver_domain'], 
        homeserver_domain=order_config['homeserver_domain'],webclient_domain=order_config['webclient_domain'],
        config=instance_config)