BEGIN TRANSACTION;
CREATE TABLE "INCIDENT" (
	`ID`         INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
	`TYPE`       TEXT NOT NULL,
    `NUMBER`     INTEGER NOT NULL,
	`NAME`       TEXT NOT NULL,
	`ACTIVE`     INTEGER NOT NULL DEFAULT 1,
    `PERSISTANT` INTEGER NOT NULL DEFAULT 0,
	`CREATED`    TEXT NOT NULL,
	`MODIFIED`   TEXT NOT NULL,
    UNIQUE(`TYPE`, `NUMBER`) ON CONFLICT FAIL
);
CREATE TABLE "ENTRY" (
	`ID`        INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
	`CATEGORY`  INTEGER NOT NULL,
	`INCIDENT`  INTEGER,
	`NOTE`      TEXT,
	`TIMESTAMP` TEXT NOT NULL UNIQUE,
	`DURATION`  INTEGER,
	`CREATED`   TEXT NOT NULL,
	`MODIFIED`  TEXT NOT NULL
);
CREATE TABLE "CATEGORY" (
	`ID`       INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
	`NAME`     INTEGER NOT NULL UNIQUE,
	`ACTIVE`   INTEGER NOT NULL DEFAULT 1,
	`CREATED`  TEXT NOT NULL,
	`MODIFIED` TEXT NOT NULL
);
CREATE VIEW VIEW_TODAYS_ENTRY AS 
SELECT
  STRFTIME('%Y-%m-%d %H:%M', ENT.TIMESTAMP) AS LOG_TIME, 
  ENT.DURATION AS MINUTES, 
  CAT.NAME, 
  INC.TYPE ||  SUBSTR('00000000' || INC.NUMBER, -8) || ' - ' ||  INC.NAME AS NAME,
  ENT.NOTE 
 FROM ENTRY AS ENT 
 LEFT JOIN CATEGORY AS CAT ON 
  ENT.CATEGORY = CAT.ID 
 LEFT JOIN INCIDENT AS INC ON 
  ENT.INCIDENT = INC.ID 
 WHERE 
  STRFTIME('%Y-%m-%d', ENT.TIMESTAMP) = DATE('now', 'localtime') 
 ORDER BY ENT.TIMESTAMP ASC;
CREATE VIEW VIEW_INCIDENTS AS
SELECT
  ID,
  NAME
FROM (SELECT
      ID,
      TYPE ||  SUBSTR('00000000' || NUMBER, -8) || ' - ' ||  NAME AS NAME
    FROM INCIDENT
    WHERE ACTIVE = 1)
ORDER BY NAME;
CREATE VIEW VIEW_ENTRY AS 
SELECT
  ENT.ID AS ENTRY_ID,
  ENT.CATEGORY AS CATEGORY_ID,
  CAT.NAME AS CATEGORY, 
  ENT.INCIDENT AS INCIDENT_ID,
  INC.TYPE ||  SUBSTR('00000000' || INC.NUMBER, -8) || ' - ' ||  INC.NAME AS INCIDENT, 
  ENT.NOTE,
  STRFTIME('%Y-%m-%d %H:%M', ENT.TIMESTAMP) AS START_TIME, 
  ENT.DURATION AS MINUTES,
  (ENT.DURATION / 60) || 'hr ' || (ENT.DURATION % 60) || 'min' AS HOURS
 FROM ENTRY AS ENT 
 LEFT JOIN CATEGORY AS CAT ON 
  ENT.CATEGORY = CAT.ID 
 LEFT JOIN INCIDENT AS INC ON 
  ENT.INCIDENT = INC.ID;
CREATE VIEW VIEW_CURRENT_TIME_SUMMARY AS SELECT STRFTIME('%Y-%m-%d', MAX(ENT.TIMESTAMP)) AS DAY, STRFTIME('%H:%M', MIN(ENT.TIMESTAMP)) AS START_TIME, STRFTIME('%H:%M', MAX(ENT.TIMESTAMP)) AS END_TIME, (SUM(ENT.DURATION) / 60) || 'hr ' || (SUM(ENT.DURATION) % 60) || 'min' AS TIME FROM ENTRY AS ENT WHERE STRFTIME('%Y-%m-%d', ENT.TIMESTAMP) = DATE('now', 'localtime');
COMMIT;
