package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path"
	"syscall"
	"time"

	dwhttp "git.arav.su/Arav/dwelling-home/internal/http"
	mfsqlite "git.arav.su/Arav/dwelling-home/pkg/mindflow/database/sqlite"
	"git.arav.su/Arav/dwelling-home/web"
	"git.arav.su/Arav/httpr"
	gb "git.arav.su/Arav/justguestbook"
)

var version string

var showVersion *bool = flag.Bool("v", false, "show version")
var listenAddress *string = flag.String("listen", "/var/run/dwelling-home/sock", "listen address (ip:port|unix_path)")
var captchaExpiry *time.Duration = flag.Duration("captcha-expiry", 10*time.Minute, "CAPTCHA expiry (e.g. 5m, 60s)")
var guestbookOwner *string = flag.String("guestbook-owner", "Admin", "name of a guestbook owner")
var guestbookPageSize *int64 = flag.Int64("guestbook-page-size", 60, "size of a guestbook page")
var databasesPath *string = flag.String("database-path", "/var/lib/dwelling-home", "path to a directory where to store DB files")

func main() {
	flag.Parse()

	if *showVersion {
		fmt.Println("dwelling-home Ver.", version, "\nCopyright (c) 2023 Alexander \"Arav\" Andreev <me@arav.su>")
		return
	}

	log.SetFlags(log.Llongfile)

	guestbookDB, err := gb.NewSQLiteDB(path.Join(*databasesPath, "guestbook.sqlite"))
	if err != nil {
		log.Fatalln(err)
	}
	defer guestbookDB.Close()

	mindflowDB, err := mfsqlite.New(path.Join(*databasesPath, "mindflow.sqlite"))
	if err != nil {
		log.Fatalln(err)
	}
	defer mindflowDB.Close()

	hand := dwhttp.NewHandlers(*captchaExpiry, *guestbookOwner, *guestbookPageSize, guestbookDB, mindflowDB)

	r := httpr.New()

	r.NotFoundHandler = func(w http.ResponseWriter, r *http.Request) {
		dwhttp.Error(w, http.StatusNotFound, "", "", r.Referer())
	}

	r.ServeStatic("/assets/*filepath", web.Assets())
	r.Handler(http.MethodGet, "/favicon.ico", dwhttp.FaviconIco)
	r.Handler(http.MethodGet, "/robots.txt", dwhttp.RobotsTxt)
	r.Handler(http.MethodGet, "/rss.xml", hand.RSS)
	r.Handler(http.MethodGet, "/sitemap.xml", dwhttp.SitemapXml)

	r.Handler(http.MethodGet, "/", hand.Index)
	r.Handler(http.MethodGet, "/privacy", hand.Privacy)
	r.Handler(http.MethodGet, "/stuff", hand.Stuff)
	r.Handler(http.MethodGet, "/stuff/article/*filepath", hand.Article)
	r.Handler(http.MethodGet, "/mindflow", hand.Mindflow)
	r.Handler(http.MethodGet, "/mindflow/admin", hand.MindflowAdmin)
	r.Handler(http.MethodGet, "/about", hand.About)
	r.Handler(http.MethodGet, "/guestbook", hand.Guestbook)
	r.Handler(http.MethodGet, "/guestbook/admin", hand.GuestbookAdmin)

	captchaApi := dwhttp.NewCaptchaApiHandlers(*captchaExpiry)

	s := r.Sub("/api/captcha")
	s.Handler(http.MethodPost, "/", captchaApi.New)
	s.Handler(http.MethodPost, "/:id", captchaApi.Solve)
	s.Handler(http.MethodGet, "/:id/image", captchaApi.Image)

	guestbookApi := dwhttp.NewGuestbookApiHandlers(*guestbookOwner, *guestbookPageSize, guestbookDB)

	s = r.Sub("/api/guestbook")
	s.Handler(http.MethodPost, "/", guestbookApi.New)
	s.Handler(http.MethodPatch, "/:id", guestbookApi.Edit)
	s.Handler(http.MethodDelete, "/:id", guestbookApi.Delete)
	s.Handler(http.MethodPost, "/:id/reply", guestbookApi.Reply)
	s.Handler(http.MethodPatch, "/:id/reply", guestbookApi.EditReply)
	s.Handler(http.MethodDelete, "/:id/reply", guestbookApi.DeleteReply)

	mindflowApi := dwhttp.NewMindflowApiHandlers(mindflowDB)

	s = r.Sub("/api/mindflow")
	s.Handler(http.MethodPost, "/", mindflowApi.NewPost)
	s.Handler(http.MethodPatch, "/:id", mindflowApi.EditPost)
	s.Handler(http.MethodDelete, "/:id", mindflowApi.DeletePost)
	s.Handler(http.MethodPost, "/category", mindflowApi.NewCategory)
	s.Handler(http.MethodPatch, "/category/:id", mindflowApi.EditCategory)
	s.Handler(http.MethodDelete, "/category/:id", mindflowApi.DeleteCategory)

	srv := dwhttp.NewHttpServer(r)

	if err := srv.Start(*listenAddress); err != nil {
		log.Fatalln(err)
	}
	defer func() {
		if err := srv.Stop(); err != nil {
			log.Fatalln(err)
		}
	}()

	doneSignal := make(chan os.Signal, 1)
	signal.Notify(doneSignal, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

	<-doneSignal
}
