import os
from django.shortcuts import render
from users.models import Users
from utils.file_upload import handle_uploaded_file
from utils.validations import validate_role
from web_admin.models import About, NewsEvent, PhotoGallery, Album


class AdminManagement:

    def __init__(self, user_type):
        self.user_type = user_type

    @validate_role
    def Dashboard(self, request):
        page_title = "BASETE RURAL DEVELOPMENT WELFARE TRUST | Dashboard"
        template = 'pages/admin/dashboard.html'
        context = {'url': 'dashboard', 'page_title': page_title,
                   'total_photo': PhotoGallery.objects.filter(is_deleted=False).count(),
                   'total_news': NewsEvent.objects.filter(is_deleted=False).count(),
                   'total_users': Users.objects.filter(is_active=True).count()
                   }
        return render(request, template, context)


    @validate_role
    def newsEvent(self, request):
        page_title = "BASETE RURAL DEVELOPMENT WELFARE TRUST | News & Events"
        template = 'pages/admin/news_event.html'
        context = {'url': 'admin-news-event', 'page_title': page_title}
        if request.method == "POST":
            if "create" in request.POST:
                title = request.POST.get("title")
                description = request.POST.get("description")
                event_date = request.POST.get("event_date")
                file_path = request.FILES['file_path']
                if file_path.name.lower().endswith(('.png', '.jpg', '.jpeg')):
                    if file_path.name.count('.') == 1:
                        if len(file_path) > 10485760:
                            context['error'] = 'Image size is too big. It must be less than or equal to 2 mb.'
                        else:
                            image_file_url = handle_uploaded_file('news', file_path)
                            image_file_path = os.path.basename(image_file_url)
                            NewsEvent(
                                title=title,
                                description=description,
                                file_path=image_file_path,
                                event_date=event_date
                            ).save()
                            context['success'] = "Successfully created."
                    else:
                        context['error'] = 'Invalid image file format!'
                else:
                    context['error'] = 'Invalid image file format!'
            elif "update" in request.POST:
                if news_event := NewsEvent.objects.filter(id=request.POST.get("id")).first():
                    if file_path := request.FILES.get('file_path', False):
                        if file_path.name.lower().endswith(('.png', '.jpg', '.jpeg')):
                            if file_path.name.count('.') == 1:
                                if len(file_path) > 10485760:
                                    context['error'] = 'Image size is too big. It must be less than or equal to 2 mb.'
                                else:
                                    image_file_url = handle_uploaded_file('news', file_path)
                                    news_event.file_path = os.path.basename(image_file_url)
                                    context['success'] = "Successfully created."
                            else:
                                context['error'] = 'Invalid image file format!'
                        else:
                            context['error'] = 'Invalid image file format!'
                    news_event.title = request.POST.get("title")
                    news_event.description = request.POST.get("description")
                    news_event.event_date = request.POST.get("event_date")
                    news_event.save()
            elif "delete" in request.POST:
                if news_event := NewsEvent.objects.filter(id=request.POST.get("id")).first():
                    news_event.is_deleted = True
                    news_event.save()
                    context['success'] = "Successfully deleted."
        context['data'] = NewsEvent.objects.filter(is_deleted=False).order_by('-id')
        return render(request, template, context)

    @validate_role
    def photoGallery(self, request):
        page_title = "BASETE RURAL DEVELOPMENT WELFARE TRUST | Photo Gallery"
        template = 'pages/admin/photo_gallery.html'
        context = {'url': 'admin-photo-gallery', 'page_title': page_title}
        if request.method == "POST":
            if "create" in request.POST:
                title = request.POST.get("title")
                description = request.POST.get("description")
                image_file = request.FILES['image_file']
                album_id = request.POST.get("album_id")
                if image_file.name.lower().endswith(('.png', '.jpg', '.jpeg')):
                    if image_file.name.count('.') == 1:
                        if len(image_file) > 10485760:
                            context['error'] = 'Image size is too big. It must be less than or equal to 2 mb.'
                        else:
                            image_file_url = handle_uploaded_file('photo_gallery', image_file)
                            image_file_path = os.path.basename(image_file_url)
                            PhotoGallery(
                                title=title,
                                description=description,
                                image_path=image_file_path,
                                album_id=album_id
                            ).save()
                            context['success'] = "Successfully created."
                    else:
                        context['error'] = 'Invalid image file format!'
                else:
                    context['error'] = 'Invalid image file format!'
            elif "update" in request.POST:
                photo_gallery_id = request.POST.get("id")
                title = request.POST.get("title")
                description = request.POST.get("description")
                if image_file := request.FILES.get('image_file', False):
                    if image_file.name.lower().endswith(('.png', '.jpg', '.jpeg')):
                        if image_file.name.count('.') == 1:
                            if len(image_file) > 10485760:
                                context['error'] = 'Image size is too big. It must be less than or equal to 2 mb.'
                            else:
                                image_file_url = handle_uploaded_file('photo_gallery', image_file)
                                image_file_path = os.path.basename(image_file_url)
                                PhotoGallery.objects.filter(id=photo_gallery_id).update(
                                    title=title,
                                    description=description,
                                    image_path=image_file_path
                                )
                                context['success'] = "Successfully updated."
                        else:
                            context['error'] = 'Invalid image file format!'
                    else:
                        context['error'] = 'Invalid image file format!'
                else:
                    PhotoGallery.objects.filter(id=photo_gallery_id).update(
                        title=title,
                        description=description
                    )
                    context['success'] = "Successfully updated."
            elif "delete" in request.POST:
                if photo_gallery := PhotoGallery.objects.filter(id=request.POST.get("id")).first():
                    photo_gallery.is_deleted = True
                    photo_gallery.save()
                    context['success'] = "Successfully Deleted."
            elif "create_album" in request.POST:
                Album.objects.create(name=request.POST.get("name"))
                context['success'] = "Successfully created."
        context['photo_galleries'] = PhotoGallery.objects.filter(is_deleted=False).order_by('-id')
        context['albums'] = Album.objects.filter(is_deleted=False).order_by('-id')
        return render(request, template, context)

 