import json
import logging

from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from waffle.models import Flag, Switch

from intranet.femida.src.api.users.serializers import AuthUserSerializer
from intranet.femida.src.frontend import nav

logger = logging.getLogger(__name__)


def get_hosts():
    return {
        'calendar': settings.CALENDAR_HOST,
        'contest': settings.CONTEST_HOST,
        'docviewer': settings.DOCVIEWER_HOST,
        'jing': settings.JING_HOST,
        'staff': settings.STAFF_HOST,
        # Нужно в любом окружении отдавать продовый staff-api
        'staffapi': 'staff-api.yandex-team.ru',
        'startrek': settings.STARTREK_HOST,
        'wiki': settings.WIKI_HOST,
        'wf': settings.WF_HOST,
        'forms': settings.FORMS_HOST,
        'idm': settings.IDM_HOST,
        'at': settings.AT_HOST,
        'hrdb': settings.HRDB_HOST,
        'search': settings.ISEARCH_FRONT_HOST,
        'geosuggest': settings.GEOSUGGEST_HOST,
    }


NOTIFIER_PREFIX = '_notifier_'
FRONTEND_PREFIX = '_frontend_'


def get_notifiers(request):
    notifiers = []
    flags = Flag.objects.filter(name__startswith=NOTIFIER_PREFIX)
    for flag in flags:
        if flag.is_active(request):
            try:
                data = json.loads(flag.note)
            except ValueError:
                logger.exception('Invalid JSON in waffle notifier: %s', flag.name)
                continue
            try:
                notifiers.append({
                    'id': flag.id,
                    'name': flag.name,
                    'text': data['text'],
                    'link': data['link'],
                })
            except KeyError:
                logger.exception('Invalid format in waffle notifier: %s', flag.name)
                continue
    return notifiers


def get_active_flags(request, prefix=None):
    flags = Flag.objects.filter(name__startswith=prefix) if prefix else Flag.objects.all()
    active_flags = [
        {
            'id': flag.id,
            'name': flag.name,
        }
        for flag in flags
        if flag.is_active(request)
    ]
    return active_flags


def get_waffle_data(request):
    return {
        'switches': dict(
            Switch.objects.values_list('name', 'active')
        ),
        'notifiers': get_notifiers(request),
        'flags': get_active_flags(request, FRONTEND_PREFIX),
    }


class AuthDataMixinBase:
    def get_auth_data(self):
        return {}


class AuthDataMixin:
    def get_auth_data(self):
        user = self.request.user
        if isinstance(user, AnonymousUser):
            auth_data = {}
        else:
            auth_data = AuthUserSerializer(user).data
            auth_data.update({
                'menu': self.get_menu(),
                'hosts': get_hosts(),
                'waffle': get_waffle_data(self.request),
                'nonce': self.csp_nonce,
            })
        return json.dumps(auth_data)

    def get_menu(self):
        menu = nav.Menu(
            nav.SimpleBlock('personal', '/'),
            nav.CandidateBlock(
                nav.DuplicationCaseBlock(),
                nav.SubmissionBlock(),
                nav.CandidateDashboardBlock(),
                nav.CandidateFilterBlock(),
                nav.CandidateCreateBlock(),
            ),
            nav.VacancyBlock(
                nav.PublicationBlock(),
                nav.SimpleBlock('applications-dashboard', '/applications/dashboard/'),
                nav.SimpleBlock('vacancy-create', '/vacancies/create/'),
            ),
            nav.SimpleBlock('interviews'),
            nav.ProblemBlock(
                nav.SimpleBlock('presets'),
                nav.SimpleBlock('complaints'),
            ),
            nav.StatsBlock(),
        )
        return menu.build(self.request.user)
