package main

import (
		"net/http"
		"log"
		"sync"
		"regexp"
		"html/template"
		"database/sql"
		_ "github.com/go-sql-driver/mysql"
		"fmt"
		"encoding/json"
)

type Page struct {
	tpl *template.Template
	Title string
	Name string
}

type LoanType struct {
	Id 		int 	`json:"id"`
	User 	int 	`json:"user"`
	Branch 	int 	`json:"branch"`
	Name 	string 	`json:"name"`
}

type FeeTemplate struct {
	Id		int 	`json:"id"`
	User	int 	`json:"user"`
	Branch	int 	`json:"branch"`
	Amount	int 	`json:"amount"`
	Perc	int 	`json:"perc"`
	Ftype	string 	`json:"type"`
	Notes	string 	`json:"notes"`
	Name	string 	`json:"name"`
	Category	string 	`json:"category"`
	Auto	bool 	`json:"auto"`
}

type Estimate struct {
	Id			int 	`json:"id"`
	User		int 	`json:"user"`
	Borrower	int 	`json:"borrower"`
	Comparison	int 	`json:"comparison"`
	Transaction	int 	`json:"transaction"`
	LoanType	LoanType `json:"loanType"`
	LoanAmount	int 	`json:"loanAmount"`
	Price		int 	`json:"price"`
	Property	string 	`json:"property"`
	Pud			bool 	`json:"pud"`
	Term		int 	`json:"term"`
	Interest	int 	`json:"interest"`
	Hoi			int 	`json:"hoi"`
	MiName		string 	`json:"miName"`
	MiAmount	int 	`json:"miAmount"`
}

var (
    regexen = make(map[string]*regexp.Regexp)
    relock  sync.Mutex
	address = "127.0.0.1:8001"
)

var paths = map[string]string {
	"home": "home.tpl",
	"terms": "terms.tpl",
	"app": "app.tpl",
}

var pages = map[string]Page {
	"home": cache("home", "Home"),
	"terms": cache("terms", "Terms and Conditions"),
	"app": cache("app", "App"),
}

func cache(name string, title string) Page {
	var p = []string{"master.tpl", paths[name]}
	tpl := template.Must(template.ParseFiles(p...))
	return Page{tpl: tpl,
				Title: title,
				Name: name,
				}
}

func (page Page) Render(w http.ResponseWriter) {
	err := page.tpl.Execute(w, page)
	if err != nil {
		log.Print(err)
	}
}

func match(path, pattern string, args *[]string) bool {
	relock.Lock()
	defer relock.Unlock()
	regex := regexen[pattern]

	if regex == nil {
		regex = regexp.MustCompile("^" + pattern + "$")
		regexen[pattern] = regex
	}

	matches := regex.FindStringSubmatch(path)
	if len(matches) <= 0 {
		return false
	}

	*args = matches[1:]
	return true
}

func getLoanType(
	db *sql.DB,
	user int,
	branch int,
	isUser bool) ([]LoanType, error) {
	var loans []LoanType

	// Should be changed to specify user
	rows, err :=
	db.Query(`SELECT * FROM loan_type WHERE user_id = ? AND branch_id = ? ` +
	"OR (user_id = 0 AND branch_id = 0)", user, branch)

	if err != nil {
		return nil, fmt.Errorf("loan_type error: %v", err)
	}

	defer rows.Close()

	for rows.Next() {
		var loan LoanType

		if err := rows.Scan(
			&loan.Id,
			&loan.User,
			&loan.Branch,
			&loan.Name)
		err != nil {
			log.Printf("Error occured fetching loan: %v", err)
			return nil, fmt.Errorf("Error occured fetching loan: %v", err)
        }

		loans = append(loans, loan)
	}

	log.Printf("The loans: %v", loans)
	return loans, nil
}

// Fetch fees from the database
func getFees(db *sql.DB, user int) ([]FeeTemplate, error) {
	var fees []FeeTemplate

	// Should be changed to specify user
	rows, err := db.Query(
		"SELECT * FROM fee_template " +
		"WHERE user_id = ? OR user_id = 0",
	user)
	if err != nil {
		return nil, fmt.Errorf("Fee error %v", err)
	}

	defer rows.Close()

	for rows.Next() {
		var fee FeeTemplate

		if err := rows.Scan(
			&fee.Id,
			&fee.User,
			&fee.Branch,
			&fee.Amount,
			&fee.Perc,
			&fee.Ftype,
			&fee.Notes,
			&fee.Name,
			&fee.Category,
			&fee.Auto)
		err != nil {
			return nil, fmt.Errorf("The fees %q: %v", user, err)
        }

		fees = append(fees, fee)
	}

	return fees, nil
}

func getMi(db *sql.DB, )

func route(w http.ResponseWriter, r *http.Request) {
    var page Page
	var args []string
    p := r.URL.Path

    switch {
    case r.Method == "GET" && match(p, "/", &args):
        page = pages[ "home" ]
    case match(p, "/terms", &args):
        page = pages[ "terms" ]
    case match(p, "/app", &args):
        page = pages[ "app" ]
    case match(p, "/assets", &args):
        page = pages[ "app" ]
    default:
        http.NotFound(w, r)
        return
    }

    page.Render(w)
}

func api(w http.ResponseWriter, r *http.Request) {
	var args []string
	// var response string
	p := r.URL.Path
	db, err := sql.Open("mysql",
		fmt.Sprintf("%s:%s@tcp(127.0.0.1:3306)/skouter",
			config["DBUser"],
			config["DBPass"]))

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")

	err = db.Ping()
	if err != nil {
		print("Bad database configuration: %v", err)
		panic(err)
		// maybe os.Exit(1) instead
	}

	switch {
	case match(p, "/api/loans", &args):
		resp, err := getLoanType(db, 0, 0, true)

		if resp != nil {
			json.NewEncoder(w).Encode(resp)
		} else {
			json.NewEncoder(w).Encode(err)
		}

	case match(p, "/api/fees", &args):
		resp, err := getFees(db, 0)

		if resp != nil {
			json.NewEncoder(w).Encode(resp)
		} else {
			json.NewEncoder(w).Encode(err)
		}
	}

}

func main() {
	files := http.FileServer(http.Dir(""))

	http.Handle("/assets/", files)
	http.HandleFunc("/api/", api)
	http.HandleFunc("/", route)
	log.Fatal(http.ListenAndServe(address, nil))
}