#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2008-2009 Zuza Software Foundation
#
# This file is part of Pootle.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.

import locale

from django.utils.translation import ugettext as _
from django.utils.translation import ungettext
from django.shortcuts import get_object_or_404
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.exceptions import PermissionDenied

from pootle_app.models import Project, Submission, Directory
from pootle_app.views.language.project_index import get_stats_headings
from pootle_app.views.language.item_dict import add_percentages, stats_descriptions
from pootle.i18n.gettext import tr_lang
from pootle_app.views.top_stats import gentopstats_project
from pootle_app.views import pagelayout
from pootle_app.models.permissions import get_matching_permissions, check_permission
from pootle_app.models.profile import get_profile

def limit(query):
    return query[:5]

def get_last_action(translation_project):
    try:
        return Submission.objects.filter(translation_project=translation_project).latest()
    except Submission.DoesNotExist:
        return ''

def make_language_item(request, translation_project):
    href = '/%s/%s/' % (translation_project.language.code, translation_project.project.code)
    projectstats = add_percentages(translation_project.getquickstats())
    info = {
        'code': translation_project.language.code,
        'href': href,
        'title': tr_lang(translation_project.language.fullname),
        'data': projectstats,
        'lastactivity': get_last_action(translation_project),
        'tooltip': _('%(percentage)d%% complete',
                     {'percentage': projectstats['translatedpercentage']})
    }
    errors = projectstats.get('errors', 0)
    if errors:
        info['errortooltip'] = ungettext('Error reading %d file', 'Error reading %d files', errors, errors)
    info.update(stats_descriptions(projectstats))
    return info

def view(request, project_code, _path_var):
    request.permissions = get_matching_permissions(get_profile(request.user), Directory.objects.root)
    if not check_permission('view', request):
        raise PermissionDenied
    project = get_object_or_404(Project, code=project_code)
    items = [make_language_item(request, translation_project) for translation_project in project.translationproject_set.iterator()]
    items.sort(lambda x, y: locale.strcoll(x['title'], y['title']))
    languagecount = len(items)
    totals = add_percentages(project.getquickstats())
    average = totals['translatedpercentage'] 

    topstats = gentopstats_project(project)

    templatevars = {
        'project': {
          'code': project.code,
          'name': project.fullname,
          'stats': ungettext('%(languages)d language, %(average)d%% translated',
                             '%(languages)d languages, %(average)d%% translated',
                             languagecount, {"languages": languagecount, "average": average})
        },
        'description': project.description,
        'adminlink': _('Admin'),
        'languages': items,
        'instancetitle': pagelayout.get_title(),
        'topstats': topstats,
        'statsheadings': get_stats_headings(),
        'translationlegend': {'translated': _('Translations are complete'),
                    'fuzzy': _('Translations need to be checked (they are marked fuzzy)'
                    ), 'untranslated': _('Untranslated')},
    }
    return render_to_response('project/project.html', templatevars, context_instance=RequestContext(request))
