# This file is part of Indico.
# Copyright (C) 2002 - 2020 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.

from __future__ import unicode_literals

from operator import attrgetter, itemgetter

from flask import flash, redirect, session
from sqlalchemy.orm import undefer

from indico.core import signals
from indico.core.db import db
from indico.modules.events.features.util import set_feature_enabled
from indico.modules.events.logs.models.entries import EventLogKind, EventLogRealm
from indico.modules.events.models.events import EventType
from indico.modules.events.payment import payment_settings
from indico.modules.events.registration import logger, registration_settings
from indico.modules.events.registration.controllers.management import RHManageRegFormBase, RHManageRegFormsBase
from indico.modules.events.registration.forms import (ParticipantsDisplayForm, ParticipantsDisplayFormColumnsForm,
                                                      RegistrationFormForm, RegistrationFormScheduleForm,
                                                      RegistrationManagersForm)
from indico.modules.events.registration.models.forms import RegistrationForm
from indico.modules.events.registration.models.items import PersonalDataType
from indico.modules.events.registration.stats import AccommodationStats, OverviewStats
from indico.modules.events.registration.util import create_personal_data_fields, get_event_section_data
from indico.modules.events.registration.views import (WPManageParticipants, WPManageRegistration,
                                                      WPManageRegistrationStats)
from indico.modules.events.util import update_object_principals
from indico.util.date_time import now_utc
from indico.util.i18n import _
from indico.web.flask.util import url_for
from indico.web.forms.base import FormDefaults
from indico.web.util import jsonify_data, jsonify_form, jsonify_template


class RHManageRegistrationForms(RHManageRegFormsBase):
    """List all registrations forms for an event"""

    def _process(self):
        regforms = (RegistrationForm.query
                    .with_parent(self.event)
                    .options(undefer('active_registration_count'))
                    .order_by(db.func.lower(RegistrationForm.title)).all())
        return WPManageRegistration.render_template('management/regform_list.html', self.event, regforms=regforms)


class RHManageRegistrationFormsDisplay(RHManageRegFormsBase):
    """Customize the display of registrations on the public page"""

    def _process(self):
        regforms = sorted(self.event.registration_forms, key=lambda f: f.title.lower())
        form = ParticipantsDisplayForm()
        if form.validate_on_submit():
            data = form.json.data
            registration_settings.set(self.event, 'merge_registration_forms', data['merge_forms'])
            registration_settings.set_participant_list_form_ids(self.event, data['participant_list_forms'])
            registration_settings.set_participant_list_columns(self.event, data['participant_list_columns'])
            for regform in regforms:
                regform.publish_registrations_enabled = regform.id in data['participant_list_forms']
            flash(_("The participants display settings have been saved."), 'success')
            return redirect(url_for('.manage_regforms_display', self.event))

        available_columns = {field[0].name: field[1]['title'] for field in PersonalDataType.FIELD_DATA}
        enabled_columns = []
        disabled_columns = []
        for column_name in registration_settings.get_participant_list_columns(self.event):
            if column_name in available_columns:
                enabled_columns.append({'id': column_name, 'title': available_columns[column_name]})
                del available_columns[column_name]
        for column_name, column_title in available_columns.iteritems():
            disabled_columns.append({'id': column_name, 'title': column_title})