#[macro_use]
extern crate diesel;

use diesel::prelude::*;
use diesel::sql_query;
use diesel::sqlite::SqliteConnection;

pub mod crud;
pub mod models;
pub mod schema;
mod utils;

pub type NxtnoteSaveFile = SqliteConnection;

pub fn initialize_file(conn: &SqliteConnection) {
    sql_query(
        "\
        CREATE TABLE blocks (
            id      BLOB NOT NULL PRIMARY KEY,
            rank    TEXT NOT NULL UNIQUE,
            type    TEXT NOT NULL
        )
    ",
    )
    .execute(conn)
    .unwrap();

    sql_query(
        "\
        CREATE TABLE block_properties (
            block_id    BLOB NOT NULL,
            name        TEXT NOT NULL,
            data        BLOB NOT NULL,
            PRIMARY KEY(block_id, name),
            FOREIGN KEY(block_id)
                REFERENCES blocks(id)
                ON DELETE CASCADE
        )
    ",
    )
    .execute(conn)
    .unwrap();
}

pub fn establish_connection(file: String) -> NxtnoteSaveFile {
    let connection = SqliteConnection::establish(&file).expect(&format!("Error connecting to {}", file));

    sql_query("PRAGMA foreign_keys = ON").execute(&connection).unwrap();

    connection
}
