module.exports = (router, passport, config, client6, upload, fs, tika, promisify, crypto, transporter) => {
    router.get('/', (req, res) => {
        return res.render('home', { user: req.user })
    })

    router.get('/login', (req, res) => {
        return res.render('login', { error: req.flash('error') })
    })

    router.post('/login', passport.authenticate('local', { failWithError: true, successRedirect: '/' }), (err, req, res, next) => {
        if (err) {
            req.flash('error', err.message)
            return res.redirect('/login')
        }
    })

    router.get('/logout', (req, res) => {
        req.logout()
        return res.redirect('/')
    })

    router.get('/register', (req, res) => {
        return res.render('register', { error: req.flash('error') })
    })

    router.post('/register', (req, res, next) => {
        if (req.body.email === req.body.email2) {
            if (req.body.username.length >= 4) {
                client6.search({
                    index: config.index,
                    body: {
                        query: {
                            match: {
                                user: req.body.username
                            }
                        }
                    }
                }, (err, user) => {
                    if (err) {
                        return next(err)
                    }
                    else if (user.body.hits.total === 0) {
                        if (req.body.password.length > 6) {
                            if (req.body.email.match(/\S+@\S+\.\S+/)) {
                                const verify_link = crypto.createHash('sha256').update(Date.now().toString()).digest('hex')
                                transporter.sendMail({
                                    from: config.mailfrom,
                                    to: req.body.email,
                                    subject: 'Verify link',
                                    text: config.mailtext(verify_link),
                                    html: config.mailhtml(verify_link)
                                }, async (error, info) => {
                                    if (error) {
                                        return next(err)
                                    } else {
                                        await client6.index({
                                            index: config.index,
                                            type: config.type,
                                            body: {
                                                date: Date.now(),
                                                user: req.body.username,
                                                password: crypto.createHash('sha256').update(req.body.password).digest('base64'),
                                                email: req.body.email,
                                                verified: false,
                                                verify_link: verify_link,
                                                documents: [],
                                                locked: false
                                            },
                                            refresh: true
                                        }).catch(err => {
                                            return next(err)
                                        })
                                        return res.render('verify', { message: info })
                                    }
                                })
                            } else {
                                req.flash('error', 'Email not valid')
                                return res.redirect('/register')
                            }
                        } else {
                            req.flash('error', 'Password must be more than 6 chars')
                            return res.redirect('/register')
                        }
                    } else {
                        req.flash('error', 'User exists')
                        return res.redirect('/register')
                    }
                })
            } else {
                req.flash('error', 'Username must be 4 or more chars')
                return res.redirect('/register')
            }
        } else {
            req.flash('error', 'Email must be the same and real')
            return res.redirect('/register')
        }
    })

    router.get('/verify', (req, res, next) => {
        if (req.query.link && req.query.link.length === 64 && req.query.link.match(/^[0-9a-f]{64}$/g)) {
            client6.search({
                index: config.index,
                body: {
                    query: {
                        match: {
                            verify_link: req.query.link
                        }
                    }
                }
            }, async (err, user) => {
                if (err) {
                    return next(err)
                } else if (user.body.hits.total === 1 && !user.body.hits.hits[0]._source.verified) {
                    await client6.update({
                        index: config.index,
                        type: config.type,
                        id: user.body.hits.hits[0]._id,
                        body: {
                            doc: {
                                verified: true
                            }
                        }
                    }).catch(err => next(err))
                    return res.redirect('/login')
                } else {
                    req.flash('error', 'Invalid user')
                    return res.redirect('/login')
                }
            })
        } else {
            req.flash('error', 'Invalid link')
            return res.redirect('/login')
        }
    })

    router.get('/upload', (req, res) => {
        return res.render('upload')
    })

    router.post('/upload', upload.array('documents', 6), (req, res, next) => {
        client6.search({
            index: config.index,
            body: {
                query: {
                    match: {
                        user: config.anonymous
                    }
                }
            }
        }, async (err, user) => {
            if (err) {
                return next(err)
            } else if (user.body.hits.total === 1 && !user.body.hits.hits[0]._source.locked) {
                const files = req.files.map(file => {
                    return promisify(tika.language)(fs.readFileSync(__dirname + '/../' + file.path).toString()).then((language, reasonablyCertain) => {
                        return promisify(tika.meta)(__dirname + '/../' + file.path, { contentType: file.mimetype }).then(async meta => {
                            delete meta['X-Parsed-By']
                            delete meta.resourceName
                            await client6.update({
                                index: config.index,
                                type: config.type,
                                id: user.body.hits.hits[0]._id,
                                body: {
                                    script: {
                                        source: 'ctx._source.documents.add(params.document)',
                                        params: {
                                            document: {
                                                date: Date.now(),
                                                originalname: file.originalname,
                                                filename: file.filename,
                                                path: file.path,
                                                mimetype: file.mimetype,
                                                size: file.size,
                                                metadata: meta,
                                                language: !file.mimetype.match(/^image/) ? language : null,
                                                sha256: crypto.createHash('sha256').update(fs.readFileSync(__dirname + '/../' + file.path)).digest('hex'),
                                                deleted: false
                                            }
                                        }
                                    }
                                },
                                refresh: 'wait_for',
                                retry_on_conflict: 6
                            }).catch(err => next(err))
                            return {
                                name: file.originalname,
                                size: file.size,
                                mime: file.mimetype,
                                language: !file.mimetype.match(/^image/) ? language : null,
                                filename: file.filename,
                                metadata: meta
                            }
                        }).catch(err => next(err))
                    }).catch(err => next(err))
                })
                Promise.all(files).then(data => {
                    return res.render('file', { documents: data })
                })
            } else {
                return next(new Error('File trouble'))
            }
        })
    })

    router.get('/error', (req, res) => {
        return res.render('error')
    })

    return router
}