// Anmeldung überprüfen und ggf. austragen


const mysql = require('mysql2')
const util = require('util')

const MYSQLHOST = process.env.MYSQLHOST || 'localhost'
const MYSQLPORT = process.env.MYSQLPORT || 3306
// const MYSQLUSER = process.env.MYSQLUSER ||  'db310927'
// const MYSQLPASSWD = process.env.MYSQLPASSWD || 'ArktUhr'
// const MYSQLDB = process.env.MYSQLDB || 'db310927'
const MYSQLUSER = process.env.MYSQLUSER ||  'root'
const MYSQLPASSWD = process.env.MYSQLPASSWD || 'SFluorit'
const MYSQLDB = process.env.MYSQLDB || 'sternwarte'



const dbConnect = () => {
	// console.log("host:", MYSQLHOST,
    //     "port:", MYSQLPORT,
    //     "user:", MYSQLUSER,
    //     "password:", MYSQLPASSWD,
    //     "database:", MYSQLDB)
    //
    const connect = mysql.createConnection({
        host: MYSQLHOST,
//	socketPath: '/var/lib/mysql/mysql.sock',
        port: MYSQLPORT,
        user: MYSQLUSER,
        password: MYSQLPASSWD,
        database: MYSQLDB
    })
    return connect;
}

const doTheQuery = async (qstr) => {
    let retur = { error: false, values: []}
    const conn = dbConnect()
    const query = util.promisify(conn.query).bind(conn)
    try {
        const rows = await query(qstr)
        retur.values = rows
    } catch(e) {
        console.log(e)
        retur.error = true
        retur.errortext = "Problems reading from database (query)"
    }
    finally{
        conn.end()
    }
    return retur
}

const holIDs = async () => {
    let ids = []
    let qstr = 'SELECT id FROM anmeldungen where name != "-" and fdatum <= 20221002'
    let erg = await doTheQuery(qstr)
    for (let x of erg.values) {
        ids.push(x)
    }
    return ids
}

const remove4WeekOlds = async (ids)  => {
    for(x of ids) {
        let qstr = `UPDATE anmeldungen SET name='-', vorname='-', email='-', telefon='-', plz=0, stadt='-', strasse='-' WHERE id=${x.id}`
        let erg = await doTheQuery(qstr)
        console.log(`id: ${x.id} => ${JSON.stringify(erg)}`)
    }
}

async function main() {
    let idarray = await holIDs()
    await remove4WeekOlds(idarray)
    console.log("Alle durch")
}

main().catch(console.error);

