const routes = require('express').Router();

const { isAdministratorUser, isLoggedUser } = require('../../middlewares/accessValidator');
const SchemaValidator = require('../../middlewares/schemaValidator');

const { cacheSuccesses } = require('../../middlewares/cache');
const PaginateMiddleware = require('../../middlewares/paginate');
const FieldMiddleware = require('../../middlewares/fields');
const SortMiddleware = require('../../middlewares/sort');

const eventController = require('./event.controller');
const eventInscriptionController = require('./events_inscriptions.controller');
const eventReservationController = require('./events_reservations.controller');
const eventQuestionController = require('./events_questions.controller');
const eventValidation = require('./event.validations');

const generalInvalidFields = [
    'userId', 'createdAt', 'updatedAt',
    'assistants', 'confirmed', 'allow_multiple', 'overflow_eventId',
    'state', 'confirmed', 
    'multiple_limit', 'marketing_list',
];

routes.get('/events', 
    isLoggedUser,
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),    
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }), 
    (req, res, next) => {
        if (!req.body.locationId)
            return eventController.find({
                scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails'],
            })(req, res, next)
        else
            return eventController.find({
                scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails', { method: ['onlyOfLocation', req.body.locationId] }]
            })(req, res, next);
    } 
);

routes.get('/events/cities',
    isLoggedUser,
    cacheSuccesses('24 hours'),
    eventController.find({
        scopes: ['CitiesOfEvents']
    })
);


routes.get('/events/next',
    isLoggedUser, 
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),    
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "init_date" }), 
    (req, res, next) => {
   //     console.log(moment().add(1, 'days').startOf('day').format('YYYY-MM-DD HH:mm:ss'));
        return eventController.find({
            scopes: ['defaultScope', 'next', 'includeVenue', 'includeMultimedias', { method: ['includeInscription', req.user.id] }],
        })(req, res, next)
    } 

);

routes.get('/events/past', 
    isLoggedUser,
    cacheSuccesses('1 minute'),
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),    
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }), 
    eventController.find({
       scopes: ['defaultScope', 'past', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);

routes.get('/events/yesterday',
    isLoggedUser,
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }),
    eventController.find({
        scopes: ['defaultScope', 'yesterday', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);


routes.get('/events/today',
    isLoggedUser,
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }),
    eventController.find({
        scopes: ['defaultScope', 'today', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);


/*routes.get('/events/today',
    isLoggedUser,
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }),

    (req, res, next) => {
        eventController.find({
            scopes: ['defaultScope', 'next', 'includeVenue', 'includeMultimedias', { method: ['includeInscription', req.user.id] }],
            })(req, res, next)
        .then (function (events) {
            console.log('>>>> ', events); //.stateCode = 'current_event';
            return events;
        });

    } 
);*/


/*
routes.get('/events/today2', (req, res, next) => {
    const events = [{
        "stateCode": "current_event",
        "stateText": "Congreso en curso",
        "id": "5f772798-aaaa-aaaa-aaaa-b6484dd11baa",
        "name": "Sevilla 2019 (prueba)",
        "description": "Os rogamos puntualidad. Una vez de comienzo el congreso el acceso no será posible hasta la siguiente ponencia o descanso.",
        "campaign_text": "Campaña \"Tu kilo también importa\". ¡Únete a nuestra campaña de recogida de alimentos! Este año 2019, en todos nuestros congresos, reuniremos alimentos no perecederos, para personas sin recursos. ¡No olvides traer tu kilo solidario el día del congreso!.\n\nEn Sevilla colaboramos con el Banco de Alimentos de Sevilla, necesitan alimentos no perecederos infantiles. Necesitan vuestra ayuda! GRACIAS!",
        "init_date": "2019-10-02T07:00:00.000Z",
        "end_date": "2019-10-02T22:30:00.000Z",
        "init_available_date": "2019-09-03T07:30:00.000Z",
        "end_available_date": "2019-10-03T22:00:00.000Z",
        "gmt": 2,
        "sold_out": false,
        "allow_overflow": true,
        "typeId": "0",
        "venueId": "ec4149e0-1958-44c0-9cfc-e64779574c82",
        "locationId": "df97179f-c8de-11e9-b18d-000c295f0f58",
        "url_streaming": "https://live.tsa.es/player/frames/lqdvi.html",
        "url_poll": null,
        "url_registration": null,
        "type": {
            "name": "conference",
            "title": "Congreso LQDVI"
        },
        "location": {
            "country": "España",
            "city": "Sevilla"
        },
        "venue": {
            "image_url": "https://cdnapp2.loquedeverdadimporta.org/cities//Sevilla.jpg",
            "id": "ec4149e0-1958-44c0-9cfc-e64779574c82",
            "name": "FIBES II, Palacio de Exposiciones y Congresos",
            "description": null,
            "address": "Avda Alcalde Luis Uruñuela 1",
            "city": "Sevilla",
            "country": "España",
            "state": null,
            "postal_code": "41000",
            "accessibility": null,
            "gmt": 2,
            "latitude": null,
            "longitude": null
        },
        "multimedias": [],
        "details": [],
        "speakers": [
            {
                "order": 648,
                "id": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                "name": "Sara Andrés",
                "description": "Sara Andrés perdió sus piernas en 2011 tras un accidente pero eso nunca le impidió empezar una nueva etapa como atleta y campeona Paralímpica Mundial.",
                "short_description": null,
                "slogan": null,
                "state": "publish",
                "typeId": "1",
                "featured": false,
                "createdAt": "2019-07-26T11:32:13.000Z",
                "updatedAt": "2019-07-26T11:32:13.000Z",
                "userId": "0939bb2a-d33d-4290-ac81-fc9faa1c015e",
                "multimedias": [
                    {
                        "id": "d3f5bc98-af88-11e9-aa90-000c295f0f58",
                        "multimediafileId": "d3f5bc98-af88-11e9-aa90-000c295f0f58",
                        "entityId": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                        "entityName": "speaker",
                        "type": "avatar",
                        "name": "Sara Andrés - picture",
                        "description": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                        "class": "picture",
                        "provider": "cdn",
                        "code": null,
                        "url": "https://cdnapp2.loquedeverdadimporta.org/speakers/sara-andres-3.jpg"
                    },
                    {
                        "id": "6c3710ea-efa3-45ce-aa51-e5e73ef22154",
                        "multimediafileId": "6c3710ea-efa3-45ce-aa51-e5e73ef22154",
                        "entityId": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                        "entityName": "speaker",
                        "type": "resume",
                        "name": "Sara Andrés - Congreso de valores LQDVI Madrid 2018",
                        "description": null,
                        "class": "video",
                        "provider": "vimeo",
                        "code": "322771046",
                        "url": "https://player.vimeo.com/video/322771046"
                    }
                ],
                "typename": "ponente",
                "rrss": {
                    "twitter": "https://twitter.com/SaraAndresB",
                    "facebook": "https://www.facebook.com/www.saraandres.es/",
                    "youtube": null,
                    "linkedin": null,
                    "instagram": null,
                    "web": "http://www.saraandres.es/"
                },
                "comments": []
            },
            {
                "order": 800,
                "id": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                "name": "Antonio Pampliega",
                "description": "Antonio Pampliega, es un periodista especializado en zonas de conflicto que fue secuestrado por el grupo terrorista Al Qaeda.",
                "short_description": "Antonio Pampliega, es un periodista especializado en zonas de conflicto que fue secuestrado por el grupo terrorista Al Qaeda.",
                "slogan": null,
                "state": "publish",
                "typeId": "1",
                "featured": false,
                "createdAt": "2019-07-26T11:32:13.000Z",
                "updatedAt": "2019-07-26T11:32:13.000Z",
                "userId": "0939bb2a-d33d-4290-ac81-fc9faa1c015e",
                "multimedias": [
                    {
                        "id": "d3f61c46-af88-11e9-aa90-000c295f0f58",
                        "multimediafileId": "d3f61c46-af88-11e9-aa90-000c295f0f58",
                        "entityId": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                        "entityName": "speaker",
                        "type": "avatar",
                        "name": "Antonio Pampliega - picture",
                        "description": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                        "class": "picture",
                        "provider": "cdn",
                        "code": null,
                        "url": "https://cdnapp2.loquedeverdadimporta.org/speakers/antonio-pampliega-3.jpg"
                    },
                    {
                        "id": "d8d7359f-b202-4ffe-8f9c-816dd9a6f510",
                        "multimediafileId": "d8d7359f-b202-4ffe-8f9c-816dd9a6f510",
                        "entityId": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                        "entityName": "speaker",
                        "type": "resume",
                        "name": "Antonio Pampliega - Congreso LQDVI Mallorca 2018",
                        "description": null,
                        "class": "video",
                        "provider": "vimeo",
                        "code": "323926045",
                        "url": "https://player.vimeo.com/video/323926045"
                    }
                ],
                "typename": "ponente",
                "rrss": {
                    "twitter": "https://twitter.com/apampliega",
                    "facebook": null,
                    "youtube": null,
                    "linkedin": null,
                    "instagram": "https://www.instagram.com/apampliega/",
                    "web": null
                },
                "comments": []
            },
            {
                "order": 778,
                "id": "c65617a7-7756-4ca1-bcc7-54a19918c4eb",
                "name": "Antonio Espinosa",
                "description": "Antonio es CEO de AUARA, empresa social cuyo fin es financiar proyectos de acceso a agua potable.",
                "short_description": "Antonio es CEO de AUARA, empresa social cuyo fin es financiar proyectos de acceso a agua potable.",
                "slogan": null,
                "state": "publish",
                "typeId": "1",
                "featured": false,
                "createdAt": "2019-07-26T11:32:13.000Z",
                "updatedAt": "2019-07-26T11:32:13.000Z",
                "userId": "0939bb2a-d33d-4290-ac81-fc9faa1c015e",
                "multimedias": [
                    {
                        "id": "d3f62532-af88-11e9-aa90-000c295f0f58",
                        "multimediafileId": "d3f62532-af88-11e9-aa90-000c295f0f58",
                        "entityId": "c65617a7-7756-4ca1-bcc7-54a19918c4eb",
                        "entityName": "speaker",
                        "type": "avatar",
                        "name": "Antonio Espinosa - picture",
                        "description": "c65617a7-7756-4ca1-bcc7-54a19918c4eb",
                        "class": "picture",
                        "provider": "cdn",
                        "code": null,
                        "url": "https://cdnapp2.loquedeverdadimporta.org/speakers/a-espinosa-3.jpg"
                    }
                ],
                "typename": "ponente",
                "rrss": {
                    "twitter": null,
                    "facebook": null,
                    "youtube": null,
                    "linkedin": "https://es.linkedin.com/in/aedlm",
                    "instagram": null,
                    "web": null
                },
                "comments": []
            }
        ],
        "partners": [
            {
                "name": "CantabriaLabs",
                "image": "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_live.jpg",
                "width": "1080",
                "height": "540",
                "link": "https://es.surveymonkey.com/r/habitos-fotoproteccion-2019"
            },
            {
                "name": "Gonvarri",
                "image": "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_live.jpg",
                "width": "1080",
                "height": "540",
                "link": "http://www.emotionaldriving.com/mensajes/"
            }
        ]
    }];

    res.set({
        'x-total-count': 1,
        'Pagination-Count': 1,
        'Pagination-Page': 1,
        'Pagination-Limit': 10,
    });    
    res.status(200).send(events);
});*/


routes.get('/events/tomorrow',
    isLoggedUser,
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }),
    eventController.find({
        scopes: ['defaultScope', 'tomorrow', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);

routes.get('/events/current', 
    isLoggedUser,
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),    
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }), 
    eventController.find({
        scopes: ['defaultScope', 'current', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);

/*routes.get('/events/5f772798-aaaa-aaaa-aaaa-b6484dd11baa', (req, res, next) => {
    const event = {
        "stateCode": "current_event",
        "stateText": "Congreso en curso",
        "id": "5f772798-aaaa-aaaa-aaaa-b6484dd11baa",
        "name": "Sevilla 2019 (prueba)",
        "description": "Os rogamos puntualidad. Una vez de comienzo el congreso el acceso no será posible hasta la siguiente ponencia o descanso.",
        "campaign_text": "Campaña \"Tu kilo también importa\". ¡Únete a nuestra campaña de recogida de alimentos! Este año 2019, en todos nuestros congresos, reuniremos alimentos no perecederos, para personas sin recursos. ¡No olvides traer tu kilo solidario el día del congreso!.\n\nEn Sevilla colaboramos con el Banco de Alimentos de Sevilla, necesitan alimentos no perecederos infantiles. Necesitan vuestra ayuda! GRACIAS!",
        "init_date": "2019-10-02T07:00:00.000Z",
        "end_date": "2019-10-02T22:30:00.000Z",
        "init_available_date": "2019-09-03T07:30:00.000Z",
        "end_available_date": "2019-10-03T22:00:00.000Z",
        "gmt": 2,
        "sold_out": false,
        "allow_overflow": true,
        "typeId": "0",
        "venueId": "ec4149e0-1958-44c0-9cfc-e64779574c82",
        "locationId": "df97179f-c8de-11e9-b18d-000c295f0f58",
        "url_streaming": "https://live.tsa.es/player/frames/lqdvi.html",
        "url_poll": null,
        "url_registration": null,
        "type": {
            "name": "conference",
            "title": "Congreso LQDVI"
        },
        "location": {
            "country": "España",
            "city": "Sevilla"
        },
        "venue": {
            "image_url": "https://cdnapp2.loquedeverdadimporta.org/cities//Sevilla.jpg",
            "id": "ec4149e0-1958-44c0-9cfc-e64779574c82",
            "name": "FIBES II, Palacio de Exposiciones y Congresos",
            "description": null,
            "address": "Avda Alcalde Luis Uruñuela 1",
            "city": "Sevilla",
            "country": "España",
            "state": null,
            "postal_code": "41000",
            "accessibility": null,
            "gmt": 2,
            "latitude": null,
            "longitude": null
        },
        "multimedias": [],
        "details": [],
        "speakers": [
            {
                "order": 648,
                "id": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                "name": "Sara Andrés",
                "description": "Sara Andrés perdió sus piernas en 2011 tras un accidente pero eso nunca le impidió empezar una nueva etapa como atleta y campeona Paralímpica Mundial.",
                "short_description": null,
                "slogan": null,
                "state": "publish",
                "typeId": "1",
                "featured": false,
                "createdAt": "2019-07-26T11:32:13.000Z",
                "updatedAt": "2019-07-26T11:32:13.000Z",
                "userId": "0939bb2a-d33d-4290-ac81-fc9faa1c015e",
                "multimedias": [
                    {
                        "id": "d3f5bc98-af88-11e9-aa90-000c295f0f58",
                        "multimediafileId": "d3f5bc98-af88-11e9-aa90-000c295f0f58",
                        "entityId": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                        "entityName": "speaker",
                        "type": "avatar",
                        "name": "Sara Andrés - picture",
                        "description": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                        "class": "picture",
                        "provider": "cdn",
                        "code": null,
                        "url": "https://cdnapp2.loquedeverdadimporta.org/speakers/sara-andres-3.jpg"
                    },
                    {
                        "id": "6c3710ea-efa3-45ce-aa51-e5e73ef22154",
                        "multimediafileId": "6c3710ea-efa3-45ce-aa51-e5e73ef22154",
                        "entityId": "72c7ca02-5559-4ca6-9505-4ead0e34e06c",
                        "entityName": "speaker",
                        "type": "resume",
                        "name": "Sara Andrés - Congreso de valores LQDVI Madrid 2018",
                        "description": null,
                        "class": "video",
                        "provider": "vimeo",
                        "code": "322771046",
                        "url": "https://player.vimeo.com/video/322771046"
                    }
                ],
                "typename": "ponente",
                "rrss": {
                    "twitter": "https://twitter.com/SaraAndresB",
                    "facebook": "https://www.facebook.com/www.saraandres.es/",
                    "youtube": null,
                    "linkedin": null,
                    "instagram": null,
                    "web": "http://www.saraandres.es/"
                },
                "comments": []
            },
            {
                "order": 800,
                "id": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                "name": "Antonio Pampliega",
                "description": "Antonio Pampliega, es un periodista especializado en zonas de conflicto que fue secuestrado por el grupo terrorista Al Qaeda.",
                "short_description": "Antonio Pampliega, es un periodista especializado en zonas de conflicto que fue secuestrado por el grupo terrorista Al Qaeda.",
                "slogan": null,
                "state": "publish",
                "typeId": "1",
                "featured": false,
                "createdAt": "2019-07-26T11:32:13.000Z",
                "updatedAt": "2019-07-26T11:32:13.000Z",
                "userId": "0939bb2a-d33d-4290-ac81-fc9faa1c015e",
                "multimedias": [
                    {
                        "id": "d3f61c46-af88-11e9-aa90-000c295f0f58",
                        "multimediafileId": "d3f61c46-af88-11e9-aa90-000c295f0f58",
                        "entityId": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                        "entityName": "speaker",
                        "type": "avatar",
                        "name": "Antonio Pampliega - picture",
                        "description": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                        "class": "picture",
                        "provider": "cdn",
                        "code": null,
                        "url": "https://cdnapp2.loquedeverdadimporta.org/speakers/antonio-pampliega-3.jpg"
                    },
                    {
                        "id": "d8d7359f-b202-4ffe-8f9c-816dd9a6f510",
                        "multimediafileId": "d8d7359f-b202-4ffe-8f9c-816dd9a6f510",
                        "entityId": "aaf594e9-3798-4ea2-b5a0-9e268277afb0",
                        "entityName": "speaker",
                        "type": "resume",
                        "name": "Antonio Pampliega - Congreso LQDVI Mallorca 2018",
                        "description": null,
                        "class": "video",
                        "provider": "vimeo",
                        "code": "323926045",
                        "url": "https://player.vimeo.com/video/323926045"
                    }
                ],
                "typename": "ponente",
                "rrss": {
                    "twitter": "https://twitter.com/apampliega",
                    "facebook": null,
                    "youtube": null,
                    "linkedin": null,
                    "instagram": "https://www.instagram.com/apampliega/",
                    "web": null
                },
                "comments": []
            },
            {
                "order": 778,
                "id": "c65617a7-7756-4ca1-bcc7-54a19918c4eb",
                "name": "Antonio Espinosa",
                "description": "Antonio es CEO de AUARA, empresa social cuyo fin es financiar proyectos de acceso a agua potable.",
                "short_description": "Antonio es CEO de AUARA, empresa social cuyo fin es financiar proyectos de acceso a agua potable.",
                "slogan": null,
                "state": "publish",
                "typeId": "1",
                "featured": false,
                "createdAt": "2019-07-26T11:32:13.000Z",
                "updatedAt": "2019-07-26T11:32:13.000Z",
                "userId": "0939bb2a-d33d-4290-ac81-fc9faa1c015e",
                "multimedias": [
                    {
                        "id": "d3f62532-af88-11e9-aa90-000c295f0f58",
                        "multimediafileId": "d3f62532-af88-11e9-aa90-000c295f0f58",
                        "entityId": "c65617a7-7756-4ca1-bcc7-54a19918c4eb",
                        "entityName": "speaker",
                        "type": "avatar",
                        "name": "Antonio Espinosa - picture",
                        "description": "c65617a7-7756-4ca1-bcc7-54a19918c4eb",
                        "class": "picture",
                        "provider": "cdn",
                        "code": null,
                        "url": "https://cdnapp2.loquedeverdadimporta.org/speakers/a-espinosa-3.jpg"
                    }
                ],
                "typename": "ponente",
                "rrss": {
                    "twitter": null,
                    "facebook": null,
                    "youtube": null,
                    "linkedin": "https://es.linkedin.com/in/aedlm",
                    "instagram": null,
                    "web": null
                },
                "comments": []
            }
        ],
        "partners": [
            {
                "name": "CantabriaLabs",
                "image": "https://cdnapp2.loquedeverdadimporta.org/partners/cantabria_labs/banner_live.jpg",
                "width": "1080",
                "height": "540",
                "link": "https://es.surveymonkey.com/r/habitos-fotoproteccion-2019"
            },
            {
                "name": "Gonvarri",
                "image": "https://cdnapp2.loquedeverdadimporta.org/partners/gonvarri/banner_live.jpg",
                "width": "1080",
                "height": "540",
                "link": "http://www.emotionaldriving.com/mensajes/"
            }
        ]
    };

    res.set({
        'x-total-count': 1,
        'Pagination-Count': 1,
        'Pagination-Page': 1,
        'Pagination-Limit': 10,
    });
    res.status(200).send(event);
});*/

routes.get('/events/:id', 
    isLoggedUser, 
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),    
    (req, res, next) => {
        return eventController.findOne({
            scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails', 'includeComments', { method: ['includeInscription', req.user.id] }]
        })(req, res, next)
    } 
);

// Comentarios

routes.get('/events/:id/comments',
    isLoggedUser, 
    (req, res, next) => {
        req.params.association = 'Comments';
        next();
    },
    eventController.find,

);

// Multimedias
routes.get('/events/:id/multimedias',
    isLoggedUser, 
    (req, res, next) => {
        req.params.association = 'Multimedias';
        next();
    },
    eventController.find,
);

// Inscripciones
// Esto da las inscripciones de un usuario
routes.get('/events/:id/inscriptions', 
    isLoggedUser,
    eventController.getInscriptions,
);


// Esto da todas las inscripciones de un usuario
routes.get('/me/inscriptions/count',
    isLoggedUser,
    /*(req, res, next) => {
        req.apicacheGroup = req.user.id;
        next();
    },
    cacheSuccesses('1 hour'),*/
    eventController.getInscriptionsOfNextEventsCount,
);

// Esto da todas las inscripciones de un usuario
routes.get('/me/inscriptions',
    isLoggedUser,
    /*(req, res, next) => {
        req.apicacheGroup = req.user.id;
        next();
    },
    cacheSuccesses('1 hour'),*/
    eventController.getInscriptions,
);

routes.get('/me/inscriptions/:id/mail',
    isLoggedUser,
    //cacheSuccesses('1 hour'),
    eventController.sendMailTicket,
);

// Esto da la inscripción de un usuario
routes.get('/me/inscriptions/:id',
    isLoggedUser,
    /*(req, res, next) => {
        req.apicacheGroup = req.user.id;
        next();
    },
    cacheSuccesses('1 hour'),*/
    eventController.getInscription,
);



/*router.get('/:conferenceId/inscription/:userId/qrimage', function (req, res) {
    conference.getInscriptionQRCode(req.params.conferenceId, req.params.userId, function (result, status) {
        if (result && result.data) {
            var buffer = new Buffer(result.data.split(",")[1], 'base64');

            res.writeHead(status, {
                'Content-Type': 'image/png',
                'Content-Length': buffer.length
            });

            res.end(buffer);
        } else {
            res.status(200).end('')
        }
    });
});*/

// Hacer una inscripción
routes.post('/events/:id/inscriptions',
    isLoggedUser, 
    SchemaValidator(eventValidation.InscriptionInputType, true), 
    eventController.createInscription
);

// Hacer una pregunta
routes.post('/events/:eventId/questions',
    isLoggedUser,
    SchemaValidator(eventValidation.EventQuestionInputType, true),
    eventQuestionController.create()
);

// Borrar una inscripción
routes.delete('/inscriptions/:id',
    isLoggedUser, 
    //SchemaValidator(eventValidation.InscriptionInputType, true),     
    eventController.deleteInscription
);


routes.get('/events/:id/reservations/:encodedInvitationCode',
    isLoggedUser, 
    //eventController.findComments
    eventController.checkReservationCode
);


//WEB

//Eventos con inscripciones abiertas para la web
routes.get('/web/events',
    //    isLoggedUser,
    FieldMiddleware.middleware({
        validFields: ['id', 'name']
    }),
    //    PaginateMiddleware.middleware(),
    //    SortMiddleware.middleware({ default: "init_available_date" }),
    eventController.find({
        scopes: ['defaultScope', 'withOpenInscriptions']
    }),
);

// Hacer una inscripción por la web
routes.post('/web/events/:id/inscriptions',
    SchemaValidator(eventValidation.webInscriptionInputType, true),
    eventController.createInscription
);

// Comprobar si estoy inscrito al congreso por la web
routes.get('/web/events/:id/inscriptions/:email',
    eventController.checkInscription
);


/*
routes.get('/tickets/:id/',
    isLoggedUser,
    eventController.findComments
);
*/

//routes.get('/venues', isLoggedUser, SortMiddleware.middleware({ default: "name" }), venueController.find);
//routes.get('/venues/:id', isLoggedUser, venueController.findOne);

//routes.post('/entity/', SchemaValidator(VenueValidation.VenueInputType, true), venueController.create);
//routes.put('/venues/:id', isAdministratorUser, venueController.update);
//routes.delete('/venues/:id', isAdministratorUser, venueController.delete);



/********************************************************************************************************
 *  ADMINISTRACIÓN   
 ********************************************************************************************************* 
 */
// Inscripciones
// Esto da las inscripciones de un evento
routes.get('/admin/events/:id/inscriptions',
    isAdministratorUser,
    eventController.getInscriptions,
);

// Todos los ponentes
routes.get('/admin/events',
    isAdministratorUser,
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }), 
    (req, res, next) => {
        if (!req.body.city)
            return eventController.find({
                scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails'],
            })(req, res, next)
        else
            return eventController.find({
                scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails', { method: ['onlyOfCity', req.body.city] }]
            })(req, res, next);
    }
);

routes.get('/admin/events/next',
    isAdministratorUser,
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "init_available_date" }),
    eventController.find({
        scopes: ['defaultScope', 'next', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);

routes.get('/admin/events/past',
    isAdministratorUser,
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }),
    eventController.find({
        scopes: ['defaultScope', 'past', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);

routes.get('/admin/events/current',
    isAdministratorUser,
    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-init_date" }),
    eventController.find({
        scopes: ['defaultScope', 'current', 'includeVenue', 'includeMultimedias', 'includeDetails'],
    }),
);

routes.get('/admin/events/:id',
    isAdministratorUser,
    (req, res, next) => {
        return eventController.findOne({
            scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeOverflowEvent', 'includeDetails']
        })(req, res, next)
    }
);

routes.get('/admin/events/:id/partners',
    isAdministratorUser,
    eventController.findPartners,    
);

routes.get('/admin/events/:id/colleges',
    isAdministratorUser,
    eventController.findColleges,
);

routes.get('/admin/events/:id/reservations/excel',
    isAdministratorUser,
    eventReservationController.getReservationsExcel,
);

routes.get('/admin/events/:id/reservations/:type/excel',
    isAdministratorUser,
    eventReservationController.getReservationsExcel,
);

routes.get('/admin/events/:id/inscriptions/excel',
    isAdministratorUser,
    eventController.getInscripcionsExcel,
);

routes.get('/admin/events/:id/reservations/:type/mail',
    isAdministratorUser,
    eventReservationController.sendMailReservationsEvent,
);

routes.get('/admin/events/:id/entity/:entityId/reservations/mail',
    isAdministratorUser,
    eventReservationController.sendMailReservationsEvent,
);


routes.get('/admin/events/:eventId/partners/:entityId/reservations',
    isAdministratorUser,
    eventReservationController.find(),
);

routes.get('/admin/events/:eventId/questions',
    isAdministratorUser,
    //    PaginateMiddleware.middleware(),
    SortMiddleware.middleware({ default: "-createdAt" }),
    eventQuestionController.find({
        scopes: ['includeUser', 'includeSpeaker'],
    }),
);


routes.get('/admin/reservations/:id',
    isAdministratorUser,
    //SchemaValidator(eventValidation.ReservationInputType, true),
    (req, res, next) => {
        return eventReservationController.findOne({
            scopes: ['includeEvent', 'includeInscriptions']
        })(req, res, next)
    },

);

routes.get('/admin/inscriptions/:id/mail',
    isAdministratorUser,
    //cacheSuccesses('1 hour'),
    eventController.sendMailTicket,
);

routes.get('/admin/reservations/:id/mail',
    isAdministratorUser,
    eventReservationController.sendMailReservation,
);


routes.post('/admin/reservations',
    isAdministratorUser,
    //SchemaValidator(eventValidation.ReservationInputType, true),
    eventReservationController.create(),

);

routes.put('/admin/reservations/:id',
    isAdministratorUser,
    //SchemaValidator(eventValidation.ReservationInputType, true),
    eventReservationController.update(),
);

//Valida una inscripción
routes.put('/admin/inscriptions/:id',
    isAdministratorUser,
    //SchemaValidator(eventValidation.ReservationInputType, true),
    eventController.validateInscription,
);

// Borrar reserva
routes.delete('/admin/reservations/:id',
    isAdministratorUser,
    eventReservationController.delete()
);



/********************************************************************************************************
 *  LIVE
 *********************************************************************************************************
 */
routes.get('/live/events/:id',
    FieldMiddleware.middleware({
        invalidFields: generalInvalidFields
    }),
    (req, res, next) => {
        return eventController.findOne({
            scopes: ['defaultScope', 'includeVenue', 'includeMultimedias', 'includeDetails']
        })(req, res, next)
    }
);

routes.get('/live/events/:eventId/speakers/:speakerId/questions',
    SortMiddleware.middleware({ default: "-createdAt" }),
    eventQuestionController.find({
        scopes: ['includeUser', 'includeSpeaker'],
    }),
);

routes.put('/live/questions/:id',
    eventQuestionController.update(),
);


module.exports = routes;