from django.contrib.gis.db import models
from django.contrib.auth.models import User
from django_extensions.db.fields import AutoSlugField
from django_countries.fields import CountryField
from django.utils.translation import ugettext as _
from django.template.defaultfilters import slugify


class CaseStudy(models.Model):
    """Model for case studies submitted to the Ojuso Platform"""

    # Choice lists for drop-downs
    SECTOR_CHOICES = (
        (_('Renewable Energy Generation'), (
            ('WND', _('Wind')),
            ('SOL', _('Solar')),
            ('HYD', _('Hydro')),
        )),
        ('PG', _('Power Grids')),
        ('SM', _('Supply of Minerals')),
    )

    POSITIVE_NEGATIVE_CHOICES = (
        ('P', _('Positive')),
        ('N', _('Negative'))
    )

    LAND_OWNERSHIP_CHOICES = (
        ('PRI', _('Private Land')),
        ('PUB', _('Public Land')),
        ('COM', _('Community Land')),
        ('OTH', _('Other')),
    )

    LOCATION_CONTEXT_CHOICES = (
        ('RUR', _('Rural')),
        ('URB', _('Urban')),
    )

    TYPE_OF_ECOSYSTEM_CHOICES = (
        (_('Water Based'), (
            ('MARINE', _('Marine (e.g. Ocean, Sea)')),
            ('FRESH', _('Freshwater (e.g. Freshwater, Lake)')),
        )),
        (_('Land Based'), (
            ('FOREST', _('Forest/Jungle')),
            ('AGRI', _('Agricultural Land')),
            ('GRASS', _('Grassland')),
            ('DESERT', _('Desert (Tundra, Ice or Sand)')),
            ('WETLND', _('Wetland (Marsh, Mangrove, Peat Soil)')),
            ('URBAN', _('Urban')),
        ))
    )

    PROJECT_STATUS_CHOICES = (
        ('EXSTNG', _('Existing Project')),
        ('UCONST', _('Under Construction')),
        ('PROJCD', _('Projected Project')),
    )

    ##
    # Meta Fields
    ##

    # User who submitted case study
    author = models.ForeignKey(
            User,
            models.SET_NULL,
            blank=True,
            null=True,
            editable=False
    )

    # Date and time of submission
    date_created = models.DateTimeField(auto_now=True, null=False)

    # Slug derived from entry_name, used in urls for SEO
    slug = AutoSlugField(populate_from=['entry_name'])

    # 1.1
    entry_name = models.CharField(
        verbose_name=_("Entry Name"),
        help_text=_("Enter the name of the entry. This should usually be the\
                   name of project."),
        max_length=128
    )

    # N/A - Not explicitly listed in spec
    location = models.PointField()

    # 1.2
    sector_of_economy = models.CharField(
        verbose_name=_("Sector of economy"),
        help_text=_("Which sector of the renewable energy economy is most\
                    relevant?"),
        max_length=3,
        choices=SECTOR_CHOICES
    )

    # 1.3
    positive_or_negative = models.CharField(
        verbose_name=_("Positive or negative?"),
        help_text=_("Is the case study a positive case or a negative case?"),
        max_length=1,
        choices=POSITIVE_NEGATIVE_CHOICES
    )

    # 1.4
    country = CountryField()

    # 1.5.1
    area_of_land = models.IntegerField(
        verbose_name=_("Approximate land area"),
        help_text=_("The area of land covered by the project (in km²)")
    )

    # 1.5.2
    land_ownership = models.CharField(
        verbose_name=_("Land ownership"),
        help_text=_("What type of ownership does the land fall under?"),
        max_length=3,
        choices=LAND_OWNERSHIP_CHOICES
    )

    # 1.5.3
    land_ownership_details = models.CharField(
        verbose_name=_("Land ownership details"),
        help_text=_("Add any details and other remarks about the land\
                    ownership"),
        max_length=256
    )

    # 1.5.4
    location_context = models.CharField(
        verbose_name=_("Location"),
        help_text=_("Select the context that is most applicable to this case\
                    study."),
        max_length=3,
        choices=LOCATION_CONTEXT_CHOICES
    )

    # 1.5.5
    type_of_ecosystem = models.CharField(
        verbose_name=_("Type of ecosystem"),
        help_text=_("Select the most relevant type of ecosystem."),
        max_length=6,
        choices=TYPE_OF_ECOSYSTEM_CHOICES,
    )

    # 1.5.5.3
    describe_ecosystem = models.CharField(
        verbose_name=_("Describe the ecosystem"),
        help_text=_("In your own words, add more detail about the ecosystem."),
        max_length=256,
    )

    # 1.5.6
    affects_indigenous = models.BooleanField(
        verbose_name=_("Affects indigenous people?"),
        help_text=_("Does the project affect indigenous people?")
    )

    # 1.5.6.1
    affects_indigenous_detail = models.CharField(
        verbose_name=_("Affects Indigenous - Details"),
        help_text=_("What group of indigenous people does the community belong\
                    to?"),
        max_length=256
    )

    # 1.6
    project_status = models.CharField(
        verbose_name=_("Status of Project"),
        help_text=_("What is the status of the current project?"),
        max_length=6,
        choices=PROJECT_STATUS_CHOICES
    )

    # 1.9
    synopsis = models.TextField(
        verbose_name=_("Synopsis"),
        help_text=_("Briefly describe the project. This will be displayed at\
                    the top of the case study page. Maximum 500 chars (about \
                    3½ tweets)"),
        max_length=500
    )

    # 1.10
    full_description = models.TextField(
        verbose_name=_("Full Description"),
        help_text=_("Describe the project in full. Separate paragraphs with a\
                    new line Please add as much detail as you feel is necessary\
                    here.")
    )

    # 1.15
    image = models.ImageField(
        verbose_name=_("Image")
    )

    # 1.16
    video = models.URLField(
        verbose_name=_("Video"),
        max_length=43
    )

    # 1.18
    community_voices = models.TextField(
        verbose_name=_("Community Voices"),
        help_text=_("Add any direct quotes from members of the community that\
                  relate to this project")
    )

    def __str__(self):
        """The String representation of the case study. (Entry name with country name.)"""
        return "%s in %s" % (self.entry_name, self.country.name)

    def clean(self, *args, **kwargs):
        """Perform validation on the model as a whole and throw a ValidationError if anything isn't how it should be."""
        pass

    def save(self, *args, **kwargs):
        """Override the save method to create a slug when the model is created. Slug is only created and never modified
        as we are basing our URLs on it and don't want it to change - ever."""
        if not self.pk:
            # Newly created object, so set slug
            self.slug = slugify(self.entry_name)
        # Continue normal save method by calling original save method.
        super(CaseStudy, self).save(*args, **kwargs)