from django.db import models
from image.models import Image
from instance.models import BaseMachineDescriptor


class ImageTemplate(BaseMachineDescriptor):
    TYPES = (
        ('SYSTEM', 'Common templates provided by the system.'),
        ('IMAGE', 'Template created from image by a user'),
        ('INSTANCE', 'Template created from instance by a user'),
    )
    image = models.ForeignKey(Image,
                              related_name="templates",
                              on_delete=models.CASCADE,
                              help_text="")
    type = models.CharField(max_length=10,
                            choices=TYPES,
                            default="SYSTEM")

    @classmethod
    def create_from_instance(cls, name, description, instance, user):
        image = Image.create_from_instance(user, instance, description)
        new_template = ImageTemplate.objects.create(name=name,
                                                    description=description,
                                                    created_by=user,
                                                    image=image,
                                                    system_type=instance.system_type,
                                                    distro=instance.distro,
                                                    access_protocol=instance.access_protocol,
                                                    lease=instance.lease,
                                                    flavor=instance.flavor,
                                                    type="INSTANCE")
        return new_template