package server

import (
	"fmt"
	"github.com/gorilla/mux"
	"gitlab.com/kbr4/svevijesti/internal/database"
	"net/http"
	"strconv"
	"time"
)

func rootHandler(wr http.ResponseWriter, req *http.Request) {
	title := "Pocetna"
	store, err := database.Connect()
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}
	defer store.Close()

	articles, err := database.ArticlesForDay(store, time.Now())
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}

	dayBefore := "/dan/" + time.Now().Add(-24*time.Hour).Format("2006-01-02")

	data := map[string]interface{}{
		"title":    title,
		"articles": articles,
		"previous": dayBefore,
		"next":     "/",
	}

	err = templates.ExecuteTemplate(wr, "homeHTML", data)
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}
}

func dailyArticlesHandler(wr http.ResponseWriter, req *http.Request) {
	vars := mux.Vars(req)
	day, err := time.Parse("2006-01-02", vars["date"])
	if err != nil {
		http.Error(wr, err.Error(), http.StatusNotFound)
	}
	dayBefore := "/dan/" + day.Add(-24*time.Hour).Format("2006-01-02")
	dayAfter := "/dan/" + day.Add(24*time.Hour).Format("2006-01-02")

	if day.Add(24*time.Hour).Format("2006-01-02") == time.Now().Format("2006-01-02") {
		dayAfter = "/"
	}

	title := fmt.Sprintf("Stare novine na dan %s", day.Format("2006-01-02"))
	store, err := database.Connect()
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}
	defer store.Close()

	articles, err := database.ArticlesForDay(store, day)
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}

	data := map[string]interface{}{
		"title":    title,
		"articles": articles,
		"previous": dayBefore,
		"next":     dayAfter,
	}

	err = templates.ExecuteTemplate(wr, "homeHTML", data)
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}
}

func articleHandler(wr http.ResponseWriter, req *http.Request) {
	store, err := database.Connect()
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}
	defer store.Close()

	vars := mux.Vars(req)
	articleID, err := strconv.Atoi(vars["id"])
	if err != nil {
		articleID = -1
	}
	articleSlug := vars["slug"]
	article, err := database.ArticleByID(store, articleID, articleSlug)
	if err != nil {
		http.Error(wr, err.Error(), http.StatusNotFound)
	}

	next, previous, _ := database.PreviousAndNextArticleUrlByID(store, articleID)

	title := article.Title
	data := map[string]interface{}{
		"title":    title,
		"article":  article,
		"previous": previous,
		"next":     next,
	}

	err = templates.ExecuteTemplate(wr, "articleHTML", data)
	if err != nil {
		http.Error(wr, err.Error(), http.StatusInternalServerError)
	}
}
