package Webserver

import (
	"log"
	"net/http"
	"strconv"

	"PersonalWebsite/Database"
	"PersonalWebsite/Helper"

	"github.com/gorilla/mux"
)

func ViewPost(w http.ResponseWriter, r *http.Request) {
	var (
		v         = make(map[string]interface{})
		urlParams map[string]string
		post      Database.Post
		e         error
	)

	urlParams = mux.Vars(r)

	post, e = Database.GetPostById(urlParams["id"])
	if e != nil {
		log.Println(e)
		http.Redirect(w, r, "/error", 302)
		return
	}

	post.Body, e = Helper.GetFileContents(post.HtmlPath)
	if e != nil {
		log.Println(e)
		http.Redirect(w, r, "/error", 302)
		return
	}

	v["Subject"] = post.Subject
	v["PageView"] = "post.gohtml"
	v["Post"] = post

	ServeTemplate(w, r, "html/index.gohtml", v)
}

func ViewPostList(w http.ResponseWriter, r *http.Request, subject string) {
	var (
		limit int = 2

		v          = make(map[string]interface{})
		posts      []Database.Post
		postsCount int64
		pageCount  int
		keys       []string
		page       int
		offset     int
		x, y       int
		ok         bool
		e          error
	)

	keys, ok = r.URL.Query()["page"]

	if !ok || len(keys[0]) < 1 {
		page = 0
	} else {
		page, e = strconv.Atoi(keys[0])
		if e != nil {
			log.Println(e)
			http.Redirect(w, r, "/error", 302)
			return
		}
	}

	offset = limit * page

	posts, e = Database.GetPostsListBySubject(limit, offset, subject)
	if e != nil {
		log.Println(e)
		http.Redirect(w, r, "/error", 302)
		return
	}

	postsCount, e = Database.GetPostCountBySubject(subject)
	if e != nil {
		log.Println(e)
		http.Redirect(w, r, "/error", 302)
		return
	}

	x, y = int(postsCount), limit
	pageCount = (x + y - 1) / y

	v["PageView"] = "post-list.gohtml"
	v["Subject"] = subject
	v["Posts"] = posts
	v["Page"] = page
	v["PageCount"] = pageCount

	ServeTemplate(w, r, "html/index.gohtml", v)
}

func ViewPostListProgramming(w http.ResponseWriter, r *http.Request) {
	ViewPostList(w, r, "Programming")
}

func ViewPostListPentesting(w http.ResponseWriter, r *http.Request) {
	ViewPostList(w, r, "Pentesting")
}
