# -*- coding: utf-8 -*-
#
# dcolumn/dcolumns/models.py
#
from __future__ import unicode_literals

"""
Dynamic Column dependent models.
"""
__docformat__ = "restructuredtext en"

import logging
import datetime
from dateutil import parser
from collections import OrderedDict

from django.db import models
from django.utils.html import format_html, format_html_join
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError

from dcolumn.common import create_field_name
from dcolumn.common.choice_mixins import BaseChoice
from dcolumn.common.model_mixins import (
    UserModelMixin, TimeModelMixin, StatusModelMixin, StatusModelManagerMixin,
    ValidateOnSaveMixin)

from .manager import dcolumn_manager

log = logging.getLogger('dcolumns.dcolumns.models')


#
# DynamicColumn
#
class DynamicColumnManager(StatusModelManagerMixin):
    """
    Supplies methods to the DynamicColumn objects instance.
    """

    def get_fk_slugs(self):
        """
        This method returns a dict of the relation model foreign key name
        and slug.

        :rtype: A dict of ``{<relation class name>: <slug>, ...}``.
        """
        result = {}

        for record in self.active():
            if record.value_type == self.model.CHOICE:
                name = dcolumn_manager.choice_relation_map.get(record.relation)
                result[name] = record.slug

        return result


class DynamicColumn(TimeModelMixin, UserModelMixin, StatusModelMixin,
                    ValidateOnSaveMixin):
    """
    This model defines all the fields used in models that implement dynamic
    columns.
    """
    BOOLEAN = 1
    CHOICE = 2
    DATE = 3
    DATETIME = 4
    FLOAT = 5
    NUMBER = 6
    TEXT = 7
    TEXT_BLOCK = 8
    TIME = 9
    VALUE_TYPES = (
        (BOOLEAN, _("Boolean")),
        (CHOICE, _("Choice")),
        (DATE, _("Date")),
        (DATETIME, _("Date Time")),
        (FLOAT, _("Floating Point")),
        (NUMBER, _("Number")),
        (TEXT, _("Text")),
        (TEXT_BLOCK, _("Text Block")),
        (TIME, _("Time")),
        )
    VALUE_TYPES_MAP = dict(VALUE_TYPES)
    NO = False
    YES = True
    YES_NO = (
        (NO, _("No")),
        (YES, _("Yes"))
        )

    name = models.CharField(
        verbose_name=_("Name"), max_length=50,
        help_text=_("Enter a column name."))
    preferred_slug = models.SlugField(
        verbose_name=_("Preferred Slug"), null=True, blank=True,
        help_text=_("If you don't want the slug to change when the name "
                    "changes enter a slug here. However, if you change this "
                    "field the slug will track it."))
    slug = models.SlugField(
        verbose_name=_("Slug"), editable=False,
        help_text=_("This field is normally created from the name field, "
                    "however, if you want to prevent it from changing when "