# This file is part of Indico.
# Copyright (C) 2002 - 2022 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.

import posixpath

from flask import current_app, render_template, request
from sqlalchemy.orm import load_only
from werkzeug.utils import cached_property

from indico.modules.admin.views import WPAdmin
from indico.modules.core.settings import social_settings
from indico.modules.events import Event
from indico.modules.events.layout import layout_settings, theme_settings
from indico.modules.events.layout.util import (build_menu_entry_name, get_css_url, get_menu_entry_by_name,
                                               menu_entries_for_event)
from indico.modules.events.management.settings import privacy_settings
from indico.modules.events.models.events import EventType
from indico.modules.events.util import serialize_event_for_json_ld
from indico.util.date_time import format_date
from indico.util.mathjax import MathjaxMixin
from indico.util.string import strip_tags, truncate
from indico.web.flask.util import url_for
from indico.web.views import WPDecorated, WPJinjaMixin


def _get_print_url(event, theme=None, theme_override=False):
    view = theme if theme_override else None
    if event.type_ == EventType.conference:
        return url_for('timetable.timetable', event, print='1', view=view)
    elif event.type_ == EventType.meeting:
        show_date = request.args.get('showDate')
        show_session = request.args.get('showSession')
        detail_level = request.args.get('detailLevel')
        if show_date == 'all':
            show_date = None
        if show_session == 'all':
            show_session = None
        if detail_level in ('all', 'contribution'):
            detail_level = None
        return url_for('events.display', event, showDate=show_date, showSession=show_session, detailLevel=detail_level,
                       print='1', view=view)
    elif event.type_ == EventType.lecture:
        return url_for('events.display', event, print='1', view=view)


def render_event_header(event, conference_layout=False, theme=None, theme_override=False):
    print_url = _get_print_url(event, theme, theme_override) if not conference_layout else None
    show_nav_bar = event.type_ != EventType.conference or layout_settings.get(event, 'show_nav_bar')
    themes = {tid: {'name': data['title'], 'user_visible': data.get('user_visible')}
              for tid, data in theme_settings.get_themes_for(event.type_.name).items()}
    return render_template('events/header.html',
                           event=event, print_url=print_url, show_nav_bar=show_nav_bar, themes=themes, theme=theme)


def render_event_footer(event, dark=False):
    location = event.venue_name
    if event.room_name:
        location = f'{event.room_name} ({location})'
    description = f'{truncate(event.description, 1000)}\n\n{event.short_external_url}'.strip()
    google_calendar_params = {
        'action': 'TEMPLATE',
        'text': event.title,
        'dates': '{}/{}'.format(event.start_dt.strftime('%Y%m%dT%H%M%SZ'),
                                event.end_dt.strftime('%Y%m%dT%H%M%SZ')),
        'details': description,
        'location': location,
        'trp': False,
        'sprop': [event.external_url, 'name:indico']
    }

    social_settings_data = social_settings.get_all()
    show_social = social_settings_data['enabled'] and layout_settings.get(event, 'show_social_badges')
    privacy_text = privacy_settings.get(event, 'privacy_policy')
    privacy_urls = privacy_settings.get(event, 'privacy_policy_urls')
    return render_template('events/footer.html',
                           event=event,
                           dark=dark,
                           social_settings=social_settings_data,
                           show_social=show_social,
                           google_calendar_params=google_calendar_params,
                           privacy_text=privacy_text,
                           privacy_urls=privacy_urls)


class WPEventAdmin(WPAdmin):
    template_prefix = 'events/'


class WPEventBase(WPDecorated):
    ALLOW_JSON = False
    bundles = ('module_events.display.js', 'module_events.contributions.js', 'module_events.header.js',