const fs = require('fs')
const crypto = require('crypto')
const sqlite3 = require('better-sqlite3')

const db = sqlite3(`./data/db.sqlite`)
db.pragma('journal_mode = WAL')

db.exec(fs.readFileSync('./data/init.sql', 'utf8'))

/*
db.exec(`attach database './data/backup.sqlite' as backup`)

db.function('backup', (tblname, ...values) => {
	db
		.prepare(`insert into backup.${tblname} select ` + values.map(e => '?').join(', '))
		.run(values)
})

const backupQuery = db
	.prepare(`
		select group_concat(tbl || char(13) || trg, char(13) || char(13)) from (
		select 'create table if not exists backup.' || t.name || ' (' || group_concat(c.name || ' ' || c.type, ', ') || ', time integer);' tbl,
		'create trigger if not exists trg_' || t.name || '_delete after delete on ' || t.name || ' for each row begin ' || 
		' select backup (' || t.name || ',' || group_concat('OLD.' || c.name, ', ') || ', strftime(''%s'', ''now'')); end;' trg
		from sqlite_master t left join pragma_table_xinfo c on t.tbl_name = c.arg and c.schema = 'main' 
		where t.sql is not null and t.type = 'table' and t.name <> 'sqlite_sequence' 
		group by t.type, t.name order by t.type, t.name)
	`)
	.pluck(true)
	.get()
db.exec(backupQuery)
*/

db.function('generate_key', (id, time) => {
	return [
		'KEY',
		Buffer.from(time + '').toString('base64'),	
		crypto.createHash('md5').update(`sa${time}-${id}lt`).digest('hex')
	].join('-')
})

process.on('exit', () => db.close())
process.on('SIGHUP', () => process.exit(128 + 1))
process.on('SIGINT', () => process.exit(128 + 2))
process.on('SIGTERM', () => process.exit(128 + 15))

db.prepareUpdate = function (table, columns, data, where) {
	const dataColumns = columns.filter(col => col in data)
	if (dataColumns.length == 0)
		throw Error('SQLite Error: No data to update')

	return db.prepare(`update "${table}" ` +
		`set ` + dataColumns.map(col => `"${col}" = :${col}`).join(', ') + 
		` where ` + where.map(col => `"${col}" = :${col}`).join(' and ')) 		
}

module.exports = db