# Path: apps/board/models.py
# class Post(BasePost):
#     """
#     게시글을 구현한 모델.
#     """
# 
#     board = models.ForeignKey(
#         Board,
#         verbose_name=_("등록 게시판"))
# 
#     board_tab = models.ManyToManyField(
#         BoardTab,
#         blank=True,
#         verbose_name=_("등록 탭"))
# 
#     title = models.CharField(
#         _("제목"),
#         max_length=128)
# 
#     tag = models.ForeignKey(
#         Tag,
#         verbose_name=_("태그"),
#         null=True, blank=True)
# 
#     is_notice = models.BooleanField(
#         _("공지글"),
#         default=False)
# 
#     class Meta:
#         verbose_name = _('포스트')
#         verbose_name_plural = _('포스트(들)')
# 
#     def __str__(self):
#         return self.title
# 
#     def get_absolute_url(self):
#         # return os.path.join(self.board.get_absolute_url(), str(self.id))
#         return self.board.get_absolute_url()+'/'+str(self.id)
# 
#     def get_first_tab(self):
#         return self.board_tab.all().first()
# 
#     def pre_permitted(self, user, permission):
#         """
#         게시글 권한 확인 이전에 게시판 접근권한을 확인하는 메서드.
#         """
#         return self.board.is_permitted(user, PERM_ACCESS)
# 
#     def post_permitted(self, user, permission):
#         """
#         게시글 권한 확인 이후에 동일 권한이 게시판에도 있는지 확인하는 메서드.
#         """
#         return self.board.is_permitted(user, permission)
# 
# Path: apps/board/serializers.py
# class PostSerializer(serializers.ModelSerializer):
# 
#     attachedfile_set = AttachedFileSerializer(many=True, read_only=True)
#     is_permitted_to_read = serializers.SerializerMethodField()
#     is_permitted_to_edit = serializers.SerializerMethodField()
#     is_permitted_to_delete = serializers.SerializerMethodField()
#     absolute_url = serializers.SerializerMethodField()
# 
#     def get_request_user(self):
#         user = None
#         request = self.context.get("request")
#         if request and hasattr(request, "user"):
#             user = request.user
#         return user
# 
#     def get_is_permitted_to_read(self, obj):
#         return obj.is_permitted(self.get_request_user(), PERM_READ)
# 
#     def get_is_permitted_to_edit(self, obj):
#         return obj.is_permitted(self.get_request_user(), PERM_EDIT)
# 
#     def get_is_permitted_to_delete(self, obj):
#         return obj.is_permitted(self.get_request_user(), PERM_DELETE)
#     
#     def get_absolute_url(self, obj):
#         return obj.get_absolute_url()
# 
#     class Meta:
#         model = Post
#         fields = (
#             'id',
#             'title',
#             'content',
#             'is_deleted',
#             'is_secret',
#             'is_permitted_to_read',
#             'is_permitted_to_edit',
#             'is_permitted_to_delete',
#             'absolute_url',
#             'board',
#             'attachedfile_set'
#         )
#         depth = 2
# 
# class CreatePostSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Post
#         fields = (
#             'title',
#             'content',
#             'board',
#         )
# 
# class RetrivePostSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Post
#         fields = (
#             'title',
#             'content',
#             'board',
#         )
# 
# Path: apps/board/constants.py
# POST_PER_PAGE = 15
# 
# BOARD_ROLE = {
#     'DEFAULT': 'DEFAULT',
#     'PROJECT': 'PROJECT',
#     'DEBATE': 'DEBATE',
#     'PLANBOOK': 'PLANBOOK',
#     'ARCHIVING':'ARCHIVING',
#     'WORKHOUR': 'WORKHOUR',
#     'SPONSOR': 'SPONSOR',
#     'SWIPER':'SWIPER',
#     'STORE': 'STORE',
#     'CONTACT':'CONTACT',
# }


from rest_framework import mixins, viewsets, permissions
from rest_framework.pagination import LimitOffsetPagination
from django.db.models import Q
from apps.board.models import Post
from apps.board.serializers import PostSerializer, CreatePostSerializer, RetrivePostSerializer
from apps.board.constants import POST_PER_PAGE, BOARD_ROLE
from apps.manager.constants import *
    permission_classes = (
        permissions.IsAdminUser,
    )
    pagination_class = PostPagination

    def get_queryset(self):
        role = self.request.query_params.get('role', None)
        search = self.request.query_params.get('search', None)
        posts = Post.objects.filter(is_deleted=False)

        # remove not permitted posts
        posts_copy = posts.all()
        for post in posts:
            if not post.is_permitted(self.request.user, PERM_READ):
                posts_copy = posts_copy.exclude(post.pk)
        posts = posts_copy
                
        if role is not None:
            posts = posts.filter(board__role__exact=role)
        if search is not None:
            posts = posts.filter(
                Q(title__icontains=search) | 
                Q(content__icontains=search)
            )
        return posts

    def get_serializer_class(self):
        if self.action == 'create':
            return CreatePostSerializer
        elif self.action == 'retrive':

# Path: apps/board/models.py
# class Post(BasePost):
#     """
#     게시글을 구현한 모델.
#     """
# 
#     board = models.ForeignKey(
#         Board,
#         verbose_name=_("등록 게시판"))
# 
#     board_tab = models.ManyToManyField(
#         BoardTab,
#         blank=True,
#         verbose_name=_("등록 탭"))
# 
#     title = models.CharField(
#         _("제목"),
#         max_length=128)
# 
#     tag = models.ForeignKey(
#         Tag,
#         verbose_name=_("태그"),
#         null=True, blank=True)
# 
#     is_notice = models.BooleanField(
#         _("공지글"),
#         default=False)
# 
#     class Meta:
#         verbose_name = _('포스트')
#         verbose_name_plural = _('포스트(들)')
# 
#     def __str__(self):
#         return self.title
# 
#     def get_absolute_url(self):
#         # return os.path.join(self.board.get_absolute_url(), str(self.id))
#         return self.board.get_absolute_url()+'/'+str(self.id)
# 
#     def get_first_tab(self):
#         return self.board_tab.all().first()
# 
#     def pre_permitted(self, user, permission):
#         """
#         게시글 권한 확인 이전에 게시판 접근권한을 확인하는 메서드.
#         """
#         return self.board.is_permitted(user, PERM_ACCESS)
# 
#     def post_permitted(self, user, permission):
#         """
#         게시글 권한 확인 이후에 동일 권한이 게시판에도 있는지 확인하는 메서드.
#         """
#         return self.board.is_permitted(user, permission)
# 
# Path: apps/board/serializers.py
# class PostSerializer(serializers.ModelSerializer):
# 
#     attachedfile_set = AttachedFileSerializer(many=True, read_only=True)
#     is_permitted_to_read = serializers.SerializerMethodField()
#     is_permitted_to_edit = serializers.SerializerMethodField()
#     is_permitted_to_delete = serializers.SerializerMethodField()
#     absolute_url = serializers.SerializerMethodField()
# 
#     def get_request_user(self):
#         user = None
#         request = self.context.get("request")
#         if request and hasattr(request, "user"):
#             user = request.user
#         return user
# 
#     def get_is_permitted_to_read(self, obj):
#         return obj.is_permitted(self.get_request_user(), PERM_READ)
# 
#     def get_is_permitted_to_edit(self, obj):
#         return obj.is_permitted(self.get_request_user(), PERM_EDIT)
# 
#     def get_is_permitted_to_delete(self, obj):
#         return obj.is_permitted(self.get_request_user(), PERM_DELETE)
#     
#     def get_absolute_url(self, obj):
#         return obj.get_absolute_url()
# 
#     class Meta:
#         model = Post
#         fields = (
#             'id',
#             'title',
#             'content',
#             'is_deleted',
#             'is_secret',
#             'is_permitted_to_read',
#             'is_permitted_to_edit',
#             'is_permitted_to_delete',
#             'absolute_url',
#             'board',
#             'attachedfile_set'
#         )
#         depth = 2
# 
# class CreatePostSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Post
#         fields = (
#             'title',
#             'content',
#             'board',
#         )
# 
# class RetrivePostSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Post
#         fields = (
#             'title',
#             'content',
#             'board',
#         )
# 
# Path: apps/board/constants.py
# POST_PER_PAGE = 15
# 
# BOARD_ROLE = {
#     'DEFAULT': 'DEFAULT',
#     'PROJECT': 'PROJECT',
#     'DEBATE': 'DEBATE',
#     'PLANBOOK': 'PLANBOOK',
#     'ARCHIVING':'ARCHIVING',
#     'WORKHOUR': 'WORKHOUR',
#     'SPONSOR': 'SPONSOR',
#     'SWIPER':'SWIPER',
#     'STORE': 'STORE',
#     'CONTACT':'CONTACT',
# }


# Path: apps/board/viewsets.py
from rest_framework import mixins, viewsets, permissions
from rest_framework.pagination import LimitOffsetPagination
from django.db.models import Q
from apps.board.models import Post
from apps.board.serializers import PostSerializer, CreatePostSerializer, RetrivePostSerializer
from apps.board.constants import POST_PER_PAGE, BOARD_ROLE
from apps.manager.constants import *

    permission_classes = (
        permissions.IsAdminUser,
    )
    pagination_class = PostPagination

    def get_queryset(self):
        role = self.request.query_params.get('role', None)
        search = self.request.query_params.get('search', None)
        posts = Post.objects.filter(is_deleted=False)

        # remove not permitted posts
        posts_copy = posts.all()
        for post in posts:
            if not post.is_permitted(self.request.user, PERM_READ):
                posts_copy = posts_copy.exclude(post.pk)
        posts = posts_copy
                
        if role is not None:
            posts = posts.filter(board__role__exact=role)
        if search is not None:
            posts = posts.filter(
                Q(title__icontains=search) | 
                Q(content__icontains=search)
            )
        return posts

    def get_serializer_class(self):
        if self.action == 'create':
            return CreatePostSerializer
        elif self.action == 'retrive':

            return RetrivePostSerializer