"use strict";

const CONF = require("./config");
const express = require("express");
const app = express();
let moment = require('moment');
const port = 3000;
const fs = require('fs');
const cors = require('cors');
let sqlite3 = require('sqlite3').verbose();
let logs = require('./log');
let db = new sqlite3.Database('./haiku.db', sqlite3.OPEN_READWRITE, (err) => {
  if (err) {
    console.error(err.message);
  } else {
    console.log(` => CONNECTED TO HAIKU DATABASE\n`);
  }
});

app.use(cors())


app.get("/api/ping", (req, res) => {
  logs.info('someone visited the site', moment().format("YYYY/MM/DD - HH:mm:ss"));
  return res.status(200).send("it's alive ..");
});

app.get("/api/get_line5_ids", (req, res) => {
  return db.all("SELECT id FROM Line5", (e, results, fields) => {
    if (e) {
      console.error(e);
      throw new Error(e);
    } else {
      let tmp = [];
      results.forEach((el) => {
        tmp.push(el['id'])
      })
      res.send(tmp);
    }
  });
});


let sql_get = (query) => {
  return new Promise((resolve, reject) => {
    db.get(query, (e, r, b) => {
      if (e) {
        console.error(e);
        reject(e);
      } else {
        resolve(r);
      }
    })
  });
}

app.post("/api/get_instance", async (req, res) => {
  try {
    let l1 = req.query.line1;
    let l2 = req.query.line2;
    let l3 = req.query.line3;
    if (!l1) {
      l1 = 1;
    }
    if (!l2) {
      l2 = 1;
    }
    if (!l3) {
      l3 = 1;
    }
    let line1 = await sql_get(`SELECT line FROM Line5 WHERE id = ${l1}`);
    let line2 = await sql_get(`SELECT line FROM Line7 WHERE id = ${l2}`);
    let line3 = await sql_get(`SELECT line FROM Line5 WHERE id = ${l3}`);
    res.send({
      line1: line1['line'],
      line2: line2['line'],
      line3: line3['line']
    });
  } catch (e) {
    console.error(e);
    throw new Error(e);
  }
});

app.get("/api/get_from_values", async (req, res) => {
  try {
    let l1 = req.query.line1;
    let l2 = req.query.line2;
    let l3 = req.query.line3;
    if (!l1) {
      l1 = 1;
    }
    if (!l2) {
      l2 = 1;
    }
    if (!l3) {
      l3 = 1;
    }

    let line1 = await sql_get(`SELECT text FROM Line5 WHERE id = ${l1}`);
    let line2 = await sql_get(`SELECT text FROM Line7 WHERE id = ${l2}`);
    let line3 = await sql_get(`SELECT text FROM Line5 WHERE id = ${l3}`);
    return {
      line1: line1['line'],
      line2: line2['line'],
      line3: line3['line']
    }
  } catch (e) {
    console.error(e);
    throw new Error(e);
  }
});

app.get("/api/get_line7_ids", (req, res) => {
  return db.all("SELECT id FROM Line7", (e, results, fields) => {
    if (e) {
      throw new Error(e);
    } else {
      let tmp = [];
      results.forEach((el) => {
        tmp.push(el['id'])
      })
      res.send(tmp);
    }
  });
});


app.listen(port, () => {
  return console.log(`\n => UDOHAIKU LISTENING ON PORT: ${port}!\n`);
});
