const mysql = require("mysql");

// prod
const VUE_APP_MYSQL_HOST = "rds7b2sll8un5kz99s0io.mysql.rds.aliyuncs.com";
const VUE_APP_MYSQL_USER_NAME = "exam_cloud";
const VUE_APP_MYSQL_PASSWORD = "examcloud123!@#";
const VUE_APP_MYSQL_DATABASE = "exam_cloud";

// test
// const VUE_APP_MYSQL_HOST = "192.168.10.30";
// const VUE_APP_MYSQL_USER_NAME = "root";
// const VUE_APP_MYSQL_PASSWORD = "root";
// const VUE_APP_MYSQL_DATABASE = "exam_cloud_test";

const connection = mysql.createConnection({
  host: VUE_APP_MYSQL_HOST,
  user: VUE_APP_MYSQL_USER_NAME,
  password: VUE_APP_MYSQL_PASSWORD,
  database: VUE_APP_MYSQL_DATABASE
});

connection.connect(err => {
  if (err) throw err;
  console.log("Database Connected! " + VUE_APP_MYSQL_HOST);
});

function queryFaceSet() {
  return new Promise((resolve, reject) => {
    connection.query(
      `SELECT faceset_token, face_count FROM ec_b_face_set order by face_count asc limit 1`,
      (err, rows) => {
        if (err) reject(err);
        console.log(rows);

        if (rows.length == 0) reject("无可用的faceset_token");
        if (rows[0].face_count > 8000) {
          reject("faceset_token最小的容量已经大于8000，无法继续。");
        } else {
          resolve(rows[0].faceset_token);
        }
      }
    );
  });
}

function updateFaceSet(faceset_token, face_count) {
  return new Promise((resolve, reject) => {
    connection.query(
      `update ec_b_face_set set face_count = ? where faceset_token = ?`,
      [face_count, faceset_token],
      (err, result) => {
        if (err) reject(err);

        console.log(`AffectedRows ${result.affectedRows} row(s)`);
        console.log(result);
        console.log(`更新 ${faceset_token} 的face_count 为 ${face_count}`);
        resolve(result);
      }
    );
  });
}

// exports.queryFaceSet = queryFaceSet;
// exports.updateFaceSet = updateFaceSet;
window.DB = {
  queryFaceSet,
  updateFaceSet
};
