const sqlite3 = require('sqlite3');
const { open } = require('sqlite');
const express = require('express');
const router = express.Router();
async function createDB() {
	return await open({
		filename: 'data.sqlite3',
		driver: sqlite3.Database
	});
}

router.get('/', async function (req, res) {
	const db = await createDB();
	const data = await db.all('SELECT * FROM personaldata');
	res.json({
		rows: data
	});
});

router.get('/:id', async function (req, res) {
	const db = await createDB();
	const data = await db.get(
		'SELECT * FROM personaldata WHERE id = ?',
		req.params.id);
	res.json({
		row: data
	});
});


router.post('/add', async function (req, res) {
	const name = req.body.name;
	const email = req.body.email;
	const db = await createDB();
	const result = await db.run(
		'INSERT INTO personaldata (name,email) values (?, ?)',
		name, email);
	res.json({
		result: result
	});
});


router.post('/edit', async (req, res) => {
	let id = req.body.id;
	let name = req.body.name;
	let email = req.body.email;
	const db = await createDB();
	let sql = 'update personaldata set name=?, email=? where id=?';
	const result = await db.run(sql, name, email, id);
	res.json({
		result: result
	});
});

module.exports = router;