const { SSL_OP_SSLEAY_080_CLIENT_DH_BUG } = require('constants')
console.log('####  OMEM-Gallery Server  ####')
console.log('by ToNetwork UG')

require('log-timestamp')
console.log('lädt: modules...')
const express = require('express')
const server = express()
const http = require('http').Server(server)
const https = require('https')
const fs = require('fs')
const path = require('path')
const cors = require('cors')
const session = require('express-session')
const basicAuth = require('express-basic-auth')
var compression = require('compression')
require('dotenv').config()

console.log('lädt: consts...')
// var privateKey = fs.readFileSync('privkey.pem').toString()
// var certificate = fs.readFileSync('cert.pem').toString()
// var credentials = { key: privateKey, cert: certificate }
let port = process.env.PORT
let portS = process.env.SSL_PORT

const sliderpath = path.join(__dirname, 'uploaded', 'slider');
const fourpicpath = path.join(__dirname, 'uploaded', '4pic');


console.log('startet server...')

server.use(cors({ origin: '*', methods: ['GET', 'POST', 'DELETE', 'UPDATE', 'PUT', 'PATCH', 'OPTIONS', 'HEAD'] }))
server.set('trust proxy', 0)
server.use(compression())
server.use(express.json())

server.use(session({ secret: 'thwGalleryOMEM1955madebyToN', cookie: { maxAge: 60000 } }))


server.get('/', function (req, res) {
    return res.send('<h1>OMEM-Gallery Server</h1><br>There is no webservice on this port!')
})


var picturelist = []
var pictureliststr = ""
var counter = 0
var count = 0


server.get('/getonepic', async function (req, res) {
    fs.readdir(sliderpath, function (err, files) {
        if (err) {
            res.status(500).send("Unable to scan directory: " + err)
            return console.log('Unable to scan directory: ' + err)
        }
        console.log(files.length)
        let newpictureliststr = ""
        files.forEach(function (file) {
            newpictureliststr += file
        })
        console.log(req.session.pictureliststr)
        console.log(newpictureliststr)
        if (req.session.pictureliststr != newpictureliststr) {
            console.log("New files in folder")
            req.session.picturelist = files
            req.session.count = files.length
            req.session.counter = 0
            req.session.pictureliststr = newpictureliststr
        }
        if (req.session.count == 0) {
            console.log("Empty directory");
            return res.status(500).send("Empty directory")
        }
        if (req.session.counter == req.session.count) {
            console.log("Starting over")
            req.session.counter = 0
        }
        let currcounter = req.session.counter
        req.session.counter++
        // res.set("Content-Disposition", 'attachment; filename="picture.png"')
        // res.set("Content-Disposition", 'inline; filename="picture.png"')
        // res.setHeader('content-type', 'image/jpeg')
        return res.status(200).sendFile(sliderpath + "/" + req.session.picturelist[currcounter], { headers: { 'Content-Type': 'image/jpeg', 'Refresh': '10;url=/getonepic' } })

    })
})

server.get('/getonepic-norefresh', async function (req, res) {
    fs.readdir(sliderpath, function (err, files) {
        if (err) {
            res.status(500).send("Unable to scan directory: " + err)
            return console.log('Unable to scan directory: ' + err)
        }
        console.log(files.length)
        let newpictureliststr = ""
        files.forEach(function (file) {
            newpictureliststr += file
        })
        console.log(req.session.pictureliststr)
        console.log(newpictureliststr)
        if (req.session.pictureliststr != newpictureliststr) {
            console.log("New files in folder")
            req.session.picturelist = files
            req.session.count = files.length
            req.session.counter = 0
            req.session.pictureliststr = newpictureliststr
        }
        if (req.session.count == 0) {
            console.log("Empty directory");
            return res.status(500).send("Empty directory")
        }
        if (req.session.counter == req.session.count) {
            console.log("Starting over")
            req.session.counter = 0
        }
        let currcounter = req.session.counter
        req.session.counter++
        // res.set("Content-Disposition", 'attachment; filename="picture.png"')
        // res.set("Content-Disposition", 'inline; filename="picture.png"')
        // res.setHeader('content-type', 'image/jpeg')
        return res.status(200).sendFile(sliderpath + "/" + req.session.picturelist[currcounter], { headers: { 'Content-Type': 'image/jpeg' } })

    })
})


server.get('/getonepic-old', async function (req, res) {
    fs.readdir(sliderpath, function (err, files) {
        if (err) {
            res.status(500).send("Unable to scan directory: " + err)
            return console.log('Unable to scan directory: ' + err)
        }
        console.log(files.length)
        let newpictureliststr = ""
        files.forEach(function (file) {
            newpictureliststr += file
        })
        console.log(pictureliststr)
        console.log(newpictureliststr)
        if (pictureliststr != newpictureliststr) {
            console.log("New files in folder")
            picturelist = files
            count = files.length
            counter = 0
            pictureliststr = newpictureliststr
        }
        if (count == 0) {
            console.log("Empty directory");
            return res.status(500).send("Empty directory")
        }
        if (counter == count) {
            console.log("Starting over")
            counter = 0
        }
        let currcounter = counter
        counter++
        // res.set("Content-Disposition", 'attachment; filename="picture.png"')
        // res.set("Content-Disposition", 'inline; filename="picture.png"')
        // res.setHeader('content-type', 'image/jpeg')
        return res.status(200).sendFile(sliderpath + "/" + picturelist[currcounter], { headers: { 'Content-Type': 'image/jpeg' } })

    })
})

server.get('/get4pic/:id', async function (req, res) {
    let currid = req.params.id
    try {
        currid = parseInt(currid)
        // if (currid == 1 || currid == 2 || currid == 3 || currid == 4) {
        // } else {
        //     throw new Error('Parameter is not in range!');
        // }
    } catch (e) {
        console.log("Unvalid ID")
        return res.status(400).send("Unvalid ID")
    }
    let currpath = ""
    let trypathjpg = fourpicpath + "/" + currid + ".jpg"
    let trypathpng = fourpicpath + "/" + currid + ".png"
    try {
        if (fs.existsSync(trypathjpg)) {
            currpath = trypathjpg
        } else if (fs.existsSync(trypathpng)) {
            currpath = trypathpng
        } else {
            console.log("No file found")
            return res.status(404).send("No file found")

        }
    } catch (err) {
        console.error(err)
        console.log("Unvalid path")
        return res.status(500).send("Unvalid path")

    }

    return res.status(200).sendFile(currpath, { headers: { 'Content-Type': 'image/jpeg' } })

})


server.get('/getonepic-test', async function (req, res) {
    fs.readdir(sliderpath, function (err, files) {
        if (err) {
            res.status(500).send("Unable to scan directory: " + err)
            return console.log('Unable to scan directory: ' + err)
        }
        console.log(files.length)
        let newpictureliststr = ""
        files.forEach(function (file) {
            newpictureliststr += file
        })
        console.log(pictureliststr)
        console.log(newpictureliststr)
        if (pictureliststr != newpictureliststr) {
            console.log("New files in folder")
            picturelist = files
            count = files.length
            counter = 0
            pictureliststr = newpictureliststr
        }
        if (count == 0) {
            console.log("Empty directory");
            return res.status(500).send("Empty directory")
        }
        if (counter == count) {
            console.log("Starting over")
            counter = 0
        }
        let currcounter = counter
        counter++
        res.set("Content-Disposition", 'attachment; filename="picture.png"')
        return res.status(200).sendFile(sliderpath + "/" + picturelist[currcounter])

    })
})





server.get('*', async function (req, res) {
    return res.status(404).send("404 - NOT FOUND - NICHT GEFUNDEN")
})

// var hsS = https.createServer(credentials, server)
// hsS.listen(portS, function() {
//     console.log('▶ HTTPS-Server läuft. Port: ' + portS)
// })
http.listen(port, function () {
    console.log('▶ HTTP-Server läuft. Port: ' + port)
})