from rest_framework import serializers
from app.applicationlayer import serializers as app_serializers
from app.entities import models
from django.db.models import Q
from app.applicationlayer.management.module.serializer import ModuleSerializer
from app.entities import enums


# Used for Create and Update
class UserManagementSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()

    class Meta:
        model = models.User
        exclude = ['password']

    def get_image(self, user):
        request = self.context.get('request')

        primayPic = user.user_images.filter(is_primary=True).first()
        if primayPic:
            return request.build_absolute_uri(primayPic.image.url)
        else:
            return request.build_absolute_uri('/media/no-user.png')


# Used for Retrieve and List
class UserManagementRoleSerializer(serializers.ModelSerializer):
    permissions = serializers.SlugRelatedField(many=True,
                                               read_only=True,
                                               slug_field='code')

    class Meta:
        model = models.Role
        fields = '__all__'
        read_only_fields = ['createdby', 'modifiedby', 'created', 'modified']


# Used for Retrieve and List
class UserManagementRetreiveSerializer(serializers.ModelSerializer):
    image = serializers.SerializerMethodField()
    applications = serializers.SerializerMethodField()
    department = serializers.SerializerMethodField()
    company = serializers.SerializerMethodField()
    create_form = serializers.SerializerMethodField()
    create_template = serializers.SerializerMethodField()

    class Meta:
        model = models.User
        fields = (
            'id',
            'create_form',
            'create_template',
            'code', 'name',
            'username', 'contact_no',
            'image', 'company',
            'department', 'applications',
            'email', 'default_app',
            'user_type', 'is_active',
            'doa',
        )
        # exclude = ['password', 'application', 'groups', 'user_permissions']


    def get_department(self, user):
        data = {
            "id": user.department.id,
            "code": user.department.code,
            "name": user.department.name
        }
        return data

    def get_company(self, user):
        data = {
            "id": user.department.company.id,
            "code": user.department.company.code,
            "name": user.department.company.name
        }
        return data

    def get_create_form(self, user):
        check_user = models.AllowedCompany.objects.filter(
            Q(id_number=user.code) &
            Q(create_change_request=True)
        ).count()
        if check_user <= 0:
            permission = False
        else:
            permission = True
        return permission

    def get_create_template(self, user):
        check_user = models.AllowedCompany.objects.filter(
            Q(id_number=user.code) &
            Q(create_change_request_template=True)
        ).count()
        if check_user <= 0:
            permission = False
        else:
            permission = True
        return permission

    def get_image(self, user):
        request = self.context.get('request')

        primayPic = user.user_images.filter(is_primary=True).first()
        if primayPic:
            return request.build_absolute_uri(primayPic.image.url)
        else:
            return request.build_absolute_uri('/media/no-user.png')

    def get_applications(self, user):
        if user.user_type.upper() == enums.UserTypeEnum.USER.value:
            app = user.application.exclude(id=1)
        else:
            rms = models.Application.objects.filter(id=1)
            app = user.application.all()
            app = app.union(app, rms)
        list_app = []

        for data in app.order_by('id'):
            if data.id == 1 and user.user_type.upper() == enums.UserTypeEnum.SUPER_USER.value:
                mod = data.modules.all()
            elif data.id == 1 and user.user_type.upper() != enums.UserTypeEnum.USER.value:
                mod = models.Module.objects.filter(
                        name__icontains="user"
                    )
            else:
                mod = data.modules.all()
            
            if user.user_type.upper() != enums.UserTypeEnum.USER.value:
                user_module = models.Module.objects.filter(name__icontains="user")
                mod = mod.union(mod, user_module)
            else:
                mod = mod
            mod = mod.order_by("parent", "sort_id")

            mod = ModuleSerializer(data=mod, many=True)
            mod.is_valid()

            app_body = {}
            app_body['app_code'] = data.code
            app_body['name'] = data.name
            app_body['modules'] = mod.data
            list_app.append(app_body)
        return list_app


class ChangePasswordSerializer(serializers.Serializer):
    old_password = serializers.CharField(max_length=100, required=True)
    new_password = serializers.CharField(max_length=100, required=True)
    new_password_confirm = serializers.CharField(max_length=100, required=True)

    class Meta:
        fields = '__all__'


# class UserSpecialPermissionSerializer(serializers.Serializer):
#     special_permissions = app_serializers.PermissionSerializer(required=True,
#                                                                many=True)

#     class Meta:
#         fields = '__all__'
