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

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

    router.post('/upload', upload.array('documents', 6), (req, res, next) => {
        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: req.user.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, user: req.user })
        })
    })

    router.get('/download-meta', (req, res, next) => {
        if (req.query.file && req.query.file.length === 32 && req.query.file.match(/^[0-9a-f]{32}$/g)) {
            client6.search({
                index: config.index,
                body: {
                    query: {
                        nested: {
                            path: 'documents',
                            query: {
                                match: {
                                    'documents.filename': req.query.file
                                }
                            }
                        }
                    }
                }
            }, async (err, user) => {
                if (err) {
                    return next(err)
                } else if (user.body.hits.total === 1 && !user.body.hits.hits[0]._source.locked) {
                    const document = user.body.hits.hits[0]._source.documents.filter(document => document.filename === req.query.file)[0]
                    fs.exists(__dirname + '/../' + document.path, exists => {
                        if (exists) {
                            const ep = new exiftool.ExiftoolProcess('/usr/bin/exiftool'),
                                read = fs.createReadStream(__dirname + '/../' + document.path),
                                write = fs.createWriteStream(`/tmp/${document.filename}`)
                            res.set('Content-Disposition', `attachment; filename="${document.originalname}"`)
                            res.set('Content-Type', 'application/octet-stream')
                            read.on('error', err => next(err))
                            write.on('error', err => next(err))
                            write.on('finish', () => {
                                ep
                                    .open()
                                    .then(() => {
                                        ep.writeMetadata(`/tmp/${document.filename}`, { all: '' }, ['overwrite_original'])
                                    })
                                    .then(console.log, err => next(err))
                                    .then(() => {
                                        ep.close()
                                        const nometa = fs.createReadStream(`/tmp/${document.filename}`)
                                        nometa.on('error', err => next(err))
                                        nometa.pipe(res)
                                    })
                                    .catch(err => next(err))
                            })
                            read.pipe(write)
                        } else {
                            return next(new Error('File not exists'))
                        }
                    })
                } else {
                    return next(new Error('File trouble'))
                }
            })
        } else {
            return next(new Error('Is not a file'))
        }
    })

    router.get('/download', (req, res, next) => {
        if (req.query.file && req.query.file.length === 32 && req.query.file.match(/^[0-9a-f]{32}$/g)) {
            client6.search({
                index: config.index,
                body: {
                    query: {
                        nested: {
                            path: 'documents',
                            query: {
                                match: {
                                    'documents.filename': req.query.file
                                }
                            }
                        }
                    }
                }
            }, async (err, user) => {
                if (err) {
                    return next(err)
                } else if (user.body.hits.total === 1 && !user.body.hits.hits[0]._source.locked) {
                    const document = user.body.hits.hits[0]._source.documents.filter(document => document.filename === req.query.file)[0]
                    fs.exists(__dirname + '/../' + document.path, exists => {
                        if (exists) {
                            res.set('Content-Disposition', `attachment; filename="${document.originalname}"`)
                            res.set('Content-Type', 'application/octet-stream')
                            fs.createReadStream(__dirname + '/../' + document.path).pipe(res)
                        } else {
                            return next(new Error('File not exists'))
                        }
                    })
                } else {
                    return next(new Error('File trouble'))
                }
            })
        } else {
            return next(new Error('Is not a file'))
        }
    })

    router.get('/files', (req, res, next) => {
        if (req.user && req.user.user) {
            client6.search({
                index: config.index,
                body: {
                    query: {
                        match: {
                            user: req.user.user
                        }
                    }
                }
            }, async (err, user) => {
                if (err) {
                    return next(err)
                } else if (user.body.hits.total === 1 && !user.body.hits.hits[0]._source.locked) {
                    const documents = user.body.hits.hits[0]._source.documents
                    res.render('files', {
                        documents: documents.filter(document => !document.deleted).map(document => {
                            return {
                                name: document.originalname,
                                size: document.size,
                                mime: document.mimetype,
                                language: document.language,
                                filename: document.filename,
                                metadata: document.metadata
                            }
                        }),
                        user: req.user
                    })
                }
            })
        } else {
            return next(new Error('User required'))
        }
    })

    router.get('/deletefile', (req, res, next) => {
        if (req.query.file && req.query.file.length === 32 && req.query.file.match(/^[0-9a-f]{32}$/g)) {
            client6.search({
                index: config.index,
                body: {
                    query: {
                        nested: {
                            path: 'documents',
                            query: {
                                match: {
                                    'documents.filename': req.query.file
                                }
                            }
                        }
                    }
                }
            }, async (err, user) => {
                if (err) {
                    return next(err)
                } else if (user.body.hits.total === 1 && !user.body.hits.hits[0]._source.locked) {
                    await client6.update({
                        index: config.index,
                        type: config.type,
                        id: user.body.hits.hits[0]._id,
                        body: {
                            script: {
                                lang: 'painless',
                                source: 'for (d in ctx._source.documents) { if (d.filename == "' + req.query.file + '") { d.deleted = true }}'
                            }
                        },
                        refresh: 'wait_for',
                        retry_on_conflict: 6
                    }).catch(err => next(err))
                    return res.redirect('/user/files')
                } else {
                    return next(new Error('File trouble'))
                }
            })
        } else {
            return next(new Error('File required'))
        }
    })
    
    return router
}