//
// Created by vfs on 02.05.2024.
//

package main

import "fmt"
import "log"
import "flag"
import "net/http"
import _ "github.com/lib/pq"
import "database/sql"
import "github.com/gorilla/sessions"
import "regexp"
import  "golang.org/x/crypto/bcrypt"

import "github.com/stripe/stripe-go/v78"
import "github.com/stripe/stripe-go/v78/customer"

var users *Usermodel

var key = []byte("super-secret-key")
var store = sessions.NewCookieStore(key)

var emailrx = regexp.MustCompile("/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/")

func secure_headers(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("X-XSS-Protection", "1; mode=block")
		w.Header().Set("X-Frame-Options", "deny")

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func require_authenticated_user(next http.HandlerFunc) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// If the user is not authenticated, redirect them to the login page and
		// return from the middleware chain so that no subsequent handlers in
		// the chain are executed.
		if authenticated_user(r) == 0 {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		}
		// Otherwise call the next handler in the chain.
		next.ServeHTTP(w, r)
	})
}

func main() {
	addr := flag.String("addr", ":8080", "HTTP network address")
	flag.Parse()
	fmt.Println("Hello, Sailor!")

	h, _ := bcrypt.GenerateFromPassword([]byte("password"), 12)

	fmt.Println(string(h))

	stripe.Key = "sk_test_51PGebgKUHKCjyTmc97rfDPcvew6EhqDz2qp3U7XoAMIilAU9IVo2NO4P7ylkTvbBafFVr94trha1VYY32jRWMw2K00Yq7YJXFf"

	c, _ := customer.Get("cus_Q7am78hLcLUvGQ", nil)

	fmt.Println(c)

	store.MaxAge(0)

	db, err := sql.Open("postgres", "postgres://elves_database:iK2SoVbDhdCki5n3LxGyP6zKpLspt4@80.240.25.87/elves_database")
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	users = &Usermodel{db}

	mux := http.NewServeMux()


	//rows, err := db.Query("SELECT * FROM accounts")
	//if err != nil {
	//	log.Fatal(err)
	//}
	//defer rows.Close()

	//accounts := make([]*Account, 0)
	//for rows.Next() {
	//	acc := new(Account)
	//	err := rows.Scan(&acc.id, &acc.Username, &acc.password, &acc.Color)
	//	if err != nil {
	//		log.Fatal(err)
	//	}
	//	accounts = append(accounts, acc)
	//}

	//if err = rows.Err(); err != nil {
	//	log.Fatal(err)
	//}

	//for _, acc := range accounts {
	//	fmt.Println(acc)
	//}

	mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))

	mux.HandleFunc("/favicon.ico", favicon)

	mux.HandleFunc("/", home)
	mux.HandleFunc("/login", login)
	mux.HandleFunc("/logout", logout)
	mux.HandleFunc("/register", register)
	mux.HandleFunc("/account", require_authenticated_user(account))
	mux.HandleFunc("/deleteaccount", require_authenticated_user(deleteaccount))


	log.Fatal(http.ListenAndServe(*addr, secure_headers(mux)))
}

//cookie := http.Cookie{
//	Name:     "exampleCookie",
//	Value:    "Hello world!",
//	Path:     "/",
//	HttpOnly: true,
//	Secure:   true,
//	SameSite: http.SameSiteLaxMode,
//}
//http.SetCookie(w, &cookie)
