# Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
# Copyright (C) 2014 Jesús Espino <jespinog@gmail.com>
# Copyright (C) 2014 David Barragán <bameda@dbarragan.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from django.db.models import Q

from taiga.base.api import ModelCrudViewSet

from taiga.projects.notifications.choices import NotifyLevel
from taiga.projects.notifications.models import Watched
from taiga.projects.models import Project
from taiga.users import services as user_services
from . import serializers
from . import models
from . import permissions
from . import services


class NotifyPolicyViewSet(ModelCrudViewSet):
    serializer_class = serializers.NotifyPolicySerializer
    permission_classes = (permissions.NotifyPolicyPermission,)

    def _build_needed_notify_policies(self):
        watched_content = user_services.get_watched_content_for_user(self.request.user)
        watched_content_project_ids = watched_content.values_list("project__id", flat=True).distinct()

        projects = Project.objects.filter(
            Q(owner=self.request.user) |
            Q(memberships__user=self.request.user) |
            Q(id__in=watched_content_project_ids)
        ).distinct()

        for project in projects:
            services.create_notify_policy_if_not_exists(project, self.request.user, NotifyLevel.watch)

    def get_queryset(self):
        if self.request.user.is_anonymous():
            return models.NotifyPolicy.objects.none()

        self._build_needed_notify_policies()

        # With really want to include the policies related to any content:
        # - The user is the owner of the project
        # - The user is member of the project
        # - The user is watching any object from the project
        watched_content = user_services.get_watched_content_for_user(self.request.user)
        watched_content_project_ids = watched_content.values_list("project__id", flat=True).distinct()
        return models.NotifyPolicy.objects.filter(Q(project__owner=self.request.user) |
            Q(project__memberships__user=self.request.user) |
            Q(project__id__in=watched_content_project_ids)
        ).distinct()
