"""
Core MozTrap models (Product).

"""
import uuid

from django.core.exceptions import ValidationError
from django.db import models

from pkg_resources import parse_version
from preferences.models import Preferences

from ..environments.models import HasEnvironmentsModel
from ..mtmodel import MTModel, MTManager, TeamModel
from ..auth.models import Role, User



class Product(MTModel, TeamModel):
    name = models.CharField(db_index=True, max_length=100)
    description = models.TextField(blank=True)


    def __unicode__(self):
        return self.name


    class Meta:
        permissions = [
            ("manage_products", "Can add/edit/delete products."),
            ("manage_users", "Can add/edit/delete user accounts."),
            ]
        ordering = ["name"]


    def clone(self, *args, **kwargs):
        """
        Clone Product, with team.

        """
        kwargs.setdefault("cascade", ["team"])
        overrides = kwargs.setdefault("overrides", {})
        overrides.setdefault("name", "Cloned: {0}".format(self.name))
        return super(Product, self).clone(*args, **kwargs)


    def reorder_versions(self, update_instance=None):
        """
        Reorder versions of this product, saving new order in db.

        If an ``update_instance`` is given, update it with new order and
        ``latest`` flag.

        """
        ordered = sorted(self.versions.all(), key=by_version)
        for i, version in enumerate(ordered, 1):
            version.order = i
            version.latest = (i == len(ordered))
            version.save(force_update=True, skip_reorder=True, notrack=True)
            if version == update_instance:
                update_instance.order = version.order
                update_instance.latest = version.latest
                update_instance.cc_version += 1
        # now we have to update latest caseversions too, @@@ too slow?
        for case in self.cases.all():
            case.set_latest_version()



class ProductVersion(MTModel, TeamModel, HasEnvironmentsModel):
    product = models.ForeignKey(Product, related_name="versions")
    version = models.CharField(max_length=100)
    codename = models.CharField(max_length=100, blank=True)
    order = models.IntegerField(default=0, editable=False)
    # denormalized for querying
    latest = models.BooleanField(default=False, editable=False)


    @property
    def name(self):
        """A ProductVersion's name is its product name and version."""
        return u"%s %s" % (self.product, self.version)


    def __unicode__(self):