CREATE DATABASE poconsole;
USE poconsole;
CREATE TABLE IF NOT EXISTS tag_classes(
    id INT NOT NULL AUTO_INCREMENT,
    tag_class varchar(64),
    description varchar(64),
    createdAt DATETIME,
    updatedAt DATETIME,
    PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS device_types(
    id INT NOT NULL AUTO_INCREMENT,
    dType VARCHAR(64),
    createdAt DATETIME,
    updatedAt DATETIME,
    PRIMARY KEY (id)
);

CREATE TABLE IF NOT EXISTS devices(
    id INT NOT NULL AUTO_INCREMENT,
    name varchar(64),
    device_type INT,
    address VARCHAR(64),
    createdAt DATETIME,
    updatedAt DATETIME,
    PRIMARY KEY (id),
    INDEX device_type_ind (device_type),
    FOREIGN KEY (device_type)
        REFERENCES device_types(id)
);

CREATE TABLE IF NOT EXISTS tags(
    id INT NOT NULL AUTO_INCREMENT,
    name varchar(128),
    class INT,
    tag varchar(128),
    deviceID INT,
    description varchar(128),
    data_type varchar(32),
    change_threshold float,
    guarantee_sec INT,
    map_function varchar(64),
    units varchar(64),
    minExpected varchar(64),
    maxExpected varchar(64),
    createdAt DATETIME,
    updatedAt DATETIME,
    PRIMARY KEY (id),
    INDEX class_ind (class),
    FOREIGN KEY (class)
        REFERENCES tag_classes(id)
        ON DELETE CASCADE,
    INDEX deviceID_ind (deviceID),
    FOREIGN KEY (deviceID)
        REFERENCES devices(id)
        ON DELETE CASCADE
);


CREATE TABLE IF NOT EXISTS tag_vals(
  id INT NOT NULL AUTO_INCREMENT,
  tagID int,
  val float,
  createdAt DATETIME,
  updatedAt DATETIME,
  PRIMARY KEY (id),
  INDEX tagID_ind (tagID),
  FOREIGN KEY (tagID)
    REFERENCES tags(id)
    ON DELETE CASCADE
);

CREATE TABLE IF NOT EXISTS config (
    id INT NOT NULL AUTO_INCREMENT,
    parameter varchar(128),
    val varchar(128),
    createdAt DATETIME,
    updatedAt DATETIME,
    PRIMARY KEY (id)
);

INSERT INTO poconsole.tag_classes (id, tag_class, description) VALUES (1, 'stroke', 'Stroke Information');
INSERT INTO poconsole.tag_classes (id, tag_class, description) VALUES (2, 'history', 'Historical Data');
INSERT INTO poconsole.tag_classes (id, tag_class, description) VALUES (3, 'gaugeoff', 'Gauge Off Data');
INSERT INTO poconsole.tag_classes (id, tag_class, description) VALUES (4, 'welltest', 'Well Test Data');
INSERT INTO poconsole.tag_classes (id, tag_class, description) VALUES (5, 'custom', 'Custom tags');

INSERT INTO poconsole.device_types (id, dType) VALUES (1, "CLX");
INSERT INTO poconsole.device_types (id, dType) VALUES (2, "Micro800");
INSERT INTO poconsole.device_types (id, dType) VALUES (3, "E300");
-- INSERT INTO poconsole.device_types (id, dType) VALUES (4, "PF755");


CREATE USER 'website'@'localhost' IDENTIFIED BY 'henrypump';
GRANT ALL ON *.* TO 'website'@'localhost';
CREATE USER 'admin'@'localhost' IDENTIFIED BY 'henrypump';
GRANT ALL ON *.* to 'admin'@'localhost';
CREATE USER 'admin'@'%' IDENTIFIED BY 'henrypump';
GRANT ALL ON *.* to 'admin'@'%';
FLUSH PRIVILEGES;
