"""
ui views
"""
import json
import logging
from urllib.parse import urlencode

from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.urls import reverse
from django.shortcuts import Http404, redirect, render
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View, TemplateView
from rolepermissions.permissions import available_perm_status
from rolepermissions.checkers import has_role

from cms.util import get_coupon_code
from courses.models import Program, Course
from ecommerce.models import Coupon
from micromasters.utils import webpack_dev_server_host
from micromasters.serializers import serialize_maybe_user
from profiles.permissions import CanSeeIfNotPrivate
from roles.models import Instructor, Staff
from ui.decorators import require_mandatory_urls
from ui.templatetags.render_bundle import public_path

log = logging.getLogger(__name__)


class ReactView(View):
    """
    Abstract view for templates using React
    """
    template_name = "dashboard.html"

    def get_context(self, request):
        """
        Get the context for the view

        Args:
            request (Request): the incoming request

        Returns:
            dict: the context object as a dictionary
        """
        user = request.user
        roles = []
        if not user.is_anonymous:
            roles = [
                {
                    'program': role.program.id,
                    'role': role.role,
                    'permissions': [perm for perm, value in available_perm_status(user).items() if value is True]
                } for role in user.role_set.all()
            ]

        js_settings = {
            "gaTrackingID": settings.GA_TRACKING_ID,
            "reactGaDebug": settings.REACT_GA_DEBUG,
            "host": webpack_dev_server_host(request),
            "edx_base_url": settings.EDXORG_BASE_URL,
            "mitxonline_base_url": settings.MITXONLINE_BASE_URL,
            "mitxonline_url": settings.MITXONLINE_URL,
            "roles": roles,
            "release_version": settings.VERSION,
            "environment": settings.ENVIRONMENT,
            "sentry_dsn": settings.SENTRY_DSN,
            "search_url": reverse('search_api', kwargs={"elastic_url": ""}),
            "support_email": settings.EMAIL_SUPPORT,
            "user": serialize_maybe_user(request.user),
            "es_page_size": settings.ELASTICSEARCH_DEFAULT_PAGE_SIZE,
            "public_path": public_path(request),
            "FEATURES": {
                "PROGRAM_LEARNERS": settings.FEATURES.get('PROGRAM_LEARNERS_ENABLED', False),
                "DISCUSSIONS_POST_UI": settings.FEATURES.get('OPEN_DISCUSSIONS_POST_UI', False),
                "DISCUSSIONS_CREATE_CHANNEL_UI": settings.FEATURES.get('OPEN_DISCUSSIONS_CREATE_CHANNEL_UI', False),
                "PROGRAM_RECORD_LINK": settings.FEATURES.get('PROGRAM_RECORD_LINK', False),
                "ENABLE_PROGRAM_LETTER": settings.FEATURES.get('ENABLE_PROGRAM_LETTER', False),
            },
            "open_discussions_redirect_url": settings.OPEN_DISCUSSIONS_REDIRECT_URL,
        }

        return {
            "has_zendesk_widget": True,
            "is_public": False,
            "google_maps_api": False,
            "js_settings_json": json.dumps(js_settings),
            "ga_tracking_id": "",
            "support_email": settings.EMAIL_SUPPORT,
        }

    def get(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """
        Handle GET requests to templates using React
        """
        return render(
            request,
            self.template_name,
            context=self.get_context(request),
        )

    def post(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """Redirect to GET. This assumes there's never any good reason to POST to these views."""
        return redirect(request.build_absolute_uri())


@method_decorator(require_mandatory_urls, name='dispatch')
@method_decorator(login_required, name='dispatch')
@method_decorator(csrf_exempt, name='dispatch')
class DashboardView(ReactView):
    """
    Wrapper for dashboard view which asserts certain logged in requirements
    """


class UsersView(ReactView):
    """
    View for learner pages. This gets handled by the dashboard view like all other
    React handled views, but we also want to return a 404 if the user does not exist.
    """
    def get(self, request, *args, **kwargs):
        """
        Handle GET requests
        """
        user = kwargs.pop('user')
        if user is not None:
            if not CanSeeIfNotPrivate().has_permission(request, self):
                raise Http404
        elif request.user.is_anonymous:
            # /learner/ redirects to logged in user's page, but user is not logged in here
            raise Http404

        return super().get(request, *args, **kwargs)


class SignInView(ReactView):
    """Sign In view"""
    template_name = "signin.html"

    def get_context(self, request):
        """
        Get the context for the view

        Args:
            request (Request): the incoming request

        Returns:
            dict: the context object as a dictionary
        """
        context = super().get_context(request)

        program_id = request.GET.get('program', None)
        next_url = request.GET.get('next', None)
        mitxonline_enabled = settings.FEATURES.get("MITXONLINE_LOGIN", False)

        program = Program.objects.filter(id=program_id[0]).first() if mitxonline_enabled and program_id else None
        params = {"next": next_url}
        return {
            **context,
            "program": program,
            "login_qs": f"?{urlencode(params)}" if next_url else '',
        }

    def get(self, request, *args, **kwargs):  # pylint: disable=unused-argument
        """
        Handle GET requests to templates using React
        """
        context = self.get_context(request)
        coupon_code = get_coupon_code(request)

        # if we didn't get a program in the context, look it up via the coupon code
        if (
            settings.FEATURES.get("MITXONLINE_LOGIN", False)
            and coupon_code
            and context["program"] is None
        ):
            program = None

            coupon = Coupon.objects.filter(coupon_code=coupon_code).first()

            if coupon is not None:
                if isinstance(coupon.content_object, Program):
                    program = coupon.content_object
                elif isinstance(coupon.content_object, Course):
                    program = coupon.content_object.program


            if program:
                params = request.GET.copy()
                params["program"] = program.id

                return redirect(
                    f"{reverse('signin')}?{params.urlencode()}",
                )

        return render(
            request,
            self.template_name,
            context=context,
        )


def standard_error_page(request, status_code, template_filename):
    """
    Returns an error page with a given template filename and provides necessary context variables
    """
    name = request.user.profile.preferred_name if not request.user.is_anonymous else ""
    authenticated = not request.user.is_anonymous
    response = render(