CREATE TABLE IF NOT EXISTS var_type (
  slabel CHAR(1) UNIQUE PRIMARY KEY,
  label VARCHAR(10) UNIQUE,
  type VARCHAR(10) NOT NULL,
  start_address INT NOT NULL DEFAULT 0,
  end_address INT NOT NULL DEFAULT 250
);

CREATE TABLE IF NOT EXISTS variable (
  type CHAR(1) NOT NULL,
  address INT NOT NULL,
  unit VARCHAR(5) NULL,
  last_update INT NULL,


  FOREIGN KEY (type) REFERENCES var_type(slabel)
    ON DELETE CASCADE,
  PRIMARY KEY(type, address)
);

CREATE TABLE IF NOT EXISTS var_value (
  type CHAR(1) NOT NULL,
  address INT NOT NULL,
  time INT DEFAULT CURRENT_TIMESTAMP,
  value INT NOT NULL,

  FOREIGN KEY (type) REFERENCES variable(type)
    ON DELETE CASCADE,
  FOREIGN KEY (address) REFERENCES variable(address)
    ON DELETE CASCADE,
  PRIMARY KEY(type, address, time)
);

INSERT INTO var_type (slabel, label, type, start_address, end_address) VALUES (
  'A', 'Analog', 'float', 1, 125);
INSERT INTO var_type (slabel, label, type, start_address, end_address) VALUES (
  'I', 'Integer', 'int', 5002, 5002 + 125);
INSERT INTO var_type (slabel, label, type, start_address, end_address) VALUES (
  'D', 'Digital', 'bool', 1, 125);

CREATE TRIGGER variable_insert BEFORE INSERT ON var_value
FOR EACH ROW
WHEN
  NOT EXISTS (
    SELECT MAX(time) FROM var_value
    WHERE
      NEW.type = type
      AND
      NEW.address = address
      AND
      NEW.value = value
  )
BEGIN
  INSERT INTO var_value
  (type, address, value)
  VALUES (NEW.type, NEW.address, NEW.value);
END;

CREATE TRIGGER variable_last_update AFTER INSERT ON var_value
FOR EACH ROW
BEGIN
  UPDATE variable
  SET last_update = NEW.time
  WHERE
    type = NEW.type
    AND
    address = NEW.address;
END;
