package main

import (
	"database/sql"
	"fmt"
	"html/template"
	"net/http"

	"github.com/go-sql-driver/mysql"
)

func getIndex(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseFiles("templates/index.tmpl")
	if err != nil {
		fmt.Println(err)
		return
	}

	err = tmpl.Execute(w, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
}

func getParamedicView(w http.ResponseWriter, r *http.Request) {
	tmpl, err := template.ParseFiles("templates/paramedicForm.tmpl")
	if err != nil {
		fmt.Println(err)
		return
	}

	err = tmpl.Execute(w, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
}

type Alert struct {
	Id int

	// Categorization
	MedicalOrTrauma string

	// Patient data
	Age       string
	Sex       string
	NhsNumber string

	// Observations
	HeartRate        string
	RespiratoryRate  string
	OxygenSaturation string
	Gcs              string
	BloodPressure    string

	// Extra information
	Eta            string
	Interventions  string
	BackgroundInfo string
}

func postParamedicForm(w http.ResponseWriter, r *http.Request) {
	// Parse data from form
	var alert Alert
	alert.MedicalOrTrauma = r.PostFormValue("medical-or-trauma")
	alert.Age = r.PostFormValue("age")
	alert.Sex = r.PostFormValue("sex")
	alert.NhsNumber = r.PostFormValue("nhs-number")
	alert.HeartRate = r.PostFormValue("heart-rate")
	alert.RespiratoryRate = r.PostFormValue("respiratory-rate")
	alert.OxygenSaturation = r.PostFormValue("oxygen-saturation")
	alert.Gcs = r.PostFormValue("gcs")
	alert.BloodPressure = r.PostFormValue("blood-pressure")
	alert.Eta = r.PostFormValue("eta")
	alert.Interventions = r.PostFormValue("interventions")
	alert.BackgroundInfo = r.PostFormValue("background")

	// Insert data into database
	query := `INSERT INTO Alert (
		MedicalOrTrauma,
		Age,
		Sex,
		NhsNumber,
		HeartRate,
		RespiratoryRate,
		OxygenSaturation,
		Gcs,
		BloodPressure,
		Eta,
		Interventions,
		BackgroundInfo) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);`

	insert, err := database.Prepare(query)
	defer insert.Close()
	if err != nil {
		fmt.Println(err)
	}

	result, err := insert.Exec(alert.MedicalOrTrauma,
		alert.Age,
		alert.Sex,
		alert.NhsNumber,
		alert.HeartRate,
		alert.RespiratoryRate,
		alert.OxygenSaturation,
		alert.Gcs,
		alert.BloodPressure,
		alert.Eta,
		alert.Interventions,
		alert.BackgroundInfo)
	rowsAffected, err := result.RowsAffected()
	if err != nil || rowsAffected != 1 {
		fmt.Println(err)
	}

	http.Redirect(w, r, "http://localhost:3333/paramedic", http.StatusFound)
}

func getERView(w http.ResponseWriter, r *http.Request) {
	// Get list of alerts from database
	alerts := []Alert{}

	rows, err := database.Query("SELECT * FROM Alert;")
	if err != nil {
		fmt.Println(err)
	}
	defer rows.Close()

	var alert Alert
	for rows.Next() {
		err := rows.Scan(&alert.Id,
			&alert.MedicalOrTrauma,
			&alert.Age,
			&alert.Sex,
			&alert.NhsNumber,
			&alert.HeartRate,
			&alert.RespiratoryRate,
			&alert.OxygenSaturation,
			&alert.Gcs,
			&alert.BloodPressure,
			&alert.Eta,
			&alert.Interventions,
			&alert.BackgroundInfo)

		if err != nil {
			fmt.Println(err)
		}

		alerts = append(alerts, alert)
	}

	for i, j := 0, len(alerts)-1; i < j; i, j = i+1, j-1 {
		alerts[i], alerts[j] = alerts[j], alerts[i]
	}

	// Execute template with list
	tmpl, err := template.ParseFiles("templates/er.tmpl")
	if err != nil {
		fmt.Println(err)
		return
	}

	err = tmpl.Execute(w, alerts)
	if err != nil {
		fmt.Println(err)
		return
	}
}

func setupDatabaseTable(db *sql.DB) {
	query := `CREATE TABLE IF NOT EXISTS Alert (
		Id SERIAL PRIMARY KEY,
		MedicalOrTrauma VARCHAR(100) NULL,
		Age VARCHAR(100) NULL,
		Sex VARCHAR(100) NULL,
		NhsNumber VARCHAR(100) NULL,
		HeartRate VARCHAR(100) NULL,
		RespiratoryRate VARCHAR(100) NULL,
		OxygenSaturation VARCHAR(100) NULL,
		Gcs VARCHAR(100) NULL,
		BloodPressure VARCHAR(100) NULL,
		Eta VARCHAR(100) NULL,
		Interventions VARCHAR(100) NULL,
		BackgroundInfo VARCHAR(100) NULL
		)`

	_, err := db.Exec(query)
	if err != nil {
		fmt.Println(err)
	}
}

var database *sql.DB

func main() {
	config := mysql.Config{
		User:                 "root",
		Passwd:               "o7MS6CIn660jIApSP",
		Net:                  "tcp",
		Addr:                 "127.0.0.1:3306",
		DBName:               "theredphone",
		AllowNativePasswords: true,
	}

	db, err := sql.Open("mysql", config.FormatDSN())
	defer db.Close()
	database = db

	if err != nil {
		fmt.Println(err)
		return
	}

	if err = db.Ping(); err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println("Connected to database")
	setupDatabaseTable(db)

	//mux := http.NewServeMux()

	http.HandleFunc("/", getIndex)
	http.HandleFunc("/paramedic", getParamedicView)
	http.HandleFunc("/paramedicForm", postParamedicForm)
	http.HandleFunc("/er", getERView)

	http.Handle("/styles/", http.StripPrefix("/styles/", http.FileServer(http.Dir("styles"))))
	http.Handle("/images/", http.StripPrefix("/images/", http.FileServer(http.Dir("images"))))

	fmt.Println("Serving")
	http.ListenAndServe(":3333", nil)
}
