#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) Pootle contributors.
#
# This file is a part of the Pootle project. It is distributed under the GPL3
# or later license. See the LICENSE file for a copy of the license and the
# AUTHORS file for copyright and authorship information.
import datetime
import difflib
import logging
import operator
import os
from hashlib import md5
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.db import models, transaction, IntegrityError
from django.db.models import F
from django.template.defaultfilters import escape, truncatechars
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.http import urlquote
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _
from translate.filters.decorators import Category
from translate.storage import base
from pootle.core.log import (TRANSLATION_ADDED, TRANSLATION_CHANGED,
                             TRANSLATION_DELETED, UNIT_ADDED, UNIT_DELETED,
                             UNIT_OBSOLETE, UNIT_RESURRECTED,
                             STORE_ADDED, STORE_OBSOLETE, STORE_DELETED,
                             MUTE_QUALITYCHECK, UNMUTE_QUALITYCHECK,
                             action_log, store_log, log)
from pootle.core.mixins import CachedMethods, CachedTreeItem
from pootle.core.models import Revision
from pootle.core.storage import PootleFileSystemStorage
from pootle.core.search import SearchBroker
from pootle.core.url_helpers import get_editor_filter, split_pootle_path
from pootle.core.utils import dateformat
from pootle.core.utils.timezone import datetime_min, make_aware
from pootle_misc.aggregate import max_column
from pootle_misc.checks import check_names, run_given_filters, get_checker
from pootle_misc.util import import_func
from pootle_statistics.models import (SubmissionFields,
                                      SubmissionTypes, Submission)
from .fields import (TranslationStoreField, MultiStringField,
                     PLURAL_PLACEHOLDER, SEPARATOR)
from .filetypes import factory_classes
from .util import OBSOLETE, UNTRANSLATED, FUZZY, TRANSLATED, get_change_str
#
# Store States
#
# Store being modified
LOCKED = -1
# Store just created, not parsed yet
NEW = 0
# Store just parsed, units added but no quality checks were run
PARSED = 1
# Quality checks run
CHECKED = 2
############### Quality Check #############
class QualityCheckManager(models.Manager):
    def get_queryset(self):
        """Mimics `select_related(depth=1)` behavior. Pending review."""
        return (
            super(QualityCheckManager, self).get_queryset().select_related(
                'unit',
            )
        )
class QualityCheck(models.Model):
    """Database cache of results of qualitychecks on unit."""
    name = models.CharField(max_length=64, db_index=True)
    unit = models.ForeignKey("pootle_store.Unit", db_index=True)
    category = models.IntegerField(null=False, default=Category.NO_CATEGORY)
    message = models.TextField()
    false_positive = models.BooleanField(default=False, db_index=True)
    objects = QualityCheckManager()
    def __unicode__(self):
        return self.name
    @property
    def display_name(self):
        return check_names.get(self.name, self.name)
    @classmethod
    def delete_unknown_checks(cls):
        unknown_checks = QualityCheck.objects \
            .exclude(name__in=check_names.keys())
        unknown_checks.delete()
################# Suggestion ################
class SuggestionManager(models.Manager):
    def get_queryset(self):
        """Mimics `select_related(depth=1)` behavior. Pending review."""
        return (
            super(SuggestionManager, self).get_queryset().select_related(
                'unit', 'user', 'reviewer',
            )
        )
    def pending(self):
        return self.get_queryset().filter(state=SuggestionStates.PENDING)
class SuggestionStates(object):
    PENDING = 'pending'
    ACCEPTED = 'accepted'
    REJECTED = 'rejected'
class Suggestion(models.Model, base.TranslationUnit):
    """Suggested translation for a :cls:`~pootle_store.models.Unit`, provided
    by users or automatically generated after a merge.
    """
    target_f = MultiStringField()
    target_hash = models.CharField(max_length=32, db_index=True)
    unit = models.ForeignKey('pootle_store.Unit')
    user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True,
                             related_name='suggestions', db_index=True)
    reviewer = models.ForeignKey(settings.AUTH_USER_MODEL, null=True,
                                 related_name='reviews', db_index=True)
    translator_comment_f = models.TextField(null=True, blank=True)
    state_choices = [
        (SuggestionStates.PENDING, _('Pending')),
        (SuggestionStates.ACCEPTED, _('Accepted')),
        (SuggestionStates.REJECTED, _('Rejected')),
    ]
    state = models.CharField(max_length=16, default=SuggestionStates.PENDING,
                             null=False, choices=state_choices, db_index=True)
    creation_time = models.DateTimeField(db_index=True, null=True)
    review_time = models.DateTimeField(null=True, db_index=True)
    objects = SuggestionManager()
    ############################ Properties ###################################
    @property
    def _target(self):
        return self.target_f
    @_target.setter
    def _target(self, value):
        self.target_f = value
        self._set_hash()
    @property
    def _source(self):
        return self.unit._source
    @property
    def translator_comment(self, value):
        return self.translator_comment_f
    @translator_comment.setter
    def translator_comment(self, value):
        self.translator_comment_f = value
        self._set_hash()
    ############################ Methods ######################################
    def __unicode__(self):
        return unicode(self.target)
    def _set_hash(self):
        string = self.translator_comment_f
        if string:
            string = self.target_f + SEPARATOR + string
        else:
            string = self.target_f
        self.target_hash = md5(string.encode("utf-8")).hexdigest()
############### Unit ####################
wordcount_f = import_func(settings.POOTLE_WORDCOUNT_FUNC)
def count_words(strings):
    wordcount = 0
    for string in strings:
        wordcount += wordcount_f(string)
    return wordcount
def stringcount(string):
    try:
        return len(string.strings)
    except AttributeError:
        return 1
TMServer = SearchBroker()
class UnitManager(models.Manager):
    def get_queryset(self):
        """Mimics `select_related(depth=1)` behavior. Pending review."""
        return (
            super(UnitManager, self).get_queryset().select_related(
                'store', 'submitted_by', 'commented_by', 'reviewed_by',
            )
        )
    def get_for_path(self, pootle_path, user):
        """Returns units that fall below the `pootle_path` umbrella.
        :param pootle_path: An internal pootle path.
        :param user: The user who is accessing the units.
        """


Answer:         lang, proj, dir_path, filename = split_pootle_path(pootle_path)