package ui

import (
	"html/template"
	"log"
	"net/http"
	"time"

	"git.streifling.com/jason/rss"
	"github.com/google/uuid"
	"streifling.com/jason/cpolis/cmd/data"
)

func ShowHub(s *data.CookieStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		session, err := s.Get(r, "cookie")
		if err != nil {
			tmpl, err := template.ParseFiles("web/templates/login.html")
			msg := "Session nicht mehr gültig. Bitte erneut anmelden."
			template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
		}

		tmpl, err := template.ParseFiles("web/templates/hub.html")
		template.Must(tmpl, err).ExecuteTemplate(w, "page-content", session.Values["role"])
	}
}

func WriteArticle(tl *data.TagList) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tmpl, err := template.ParseFiles("web/templates/editor.html")
		template.Must(tmpl, err).ExecuteTemplate(w, "page-content", tl.Get())
	}
}

func FinishArticle(al *data.ArticleList, s *data.CookieStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		article := new(data.Article)
		var err error

		article.Title, err = data.ConvertToPlain(r.PostFormValue("editor-title"))
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		article.Desc, err = data.ConvertToPlain(r.PostFormValue("editor-desc"))
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		article.Content, err = data.ConvertToHTML(r.PostFormValue("editor-text"))
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		r.ParseForm()
		article.Tags = append(article.Tags, r.Form["tags"]...)

		session, err := s.Get(r, "cookie")
		if err != nil {
			tmpl, err := template.ParseFiles("web/templates/login.html")
			msg := "Session nicht mehr gültig. Bitte erneut anmelden."
			template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
		}

		article.UUID = uuid.New()
		article.Author = session.Values["name"].(string)
		article.Created = time.Now()
		article.AuthorID = session.Values["id"].(int64)

		al.Add(article)
		al.Save("tmp/unpublished-articles.gob")

		tmpl, err := template.ParseFiles("web/templates/hub.html")
		tmpl = template.Must(tmpl, err)
		tmpl.ExecuteTemplate(w, "page-content", session.Values["role"])
	}
}

func ShowUnpublishedArticles(al *data.ArticleList) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		tmpl, err := template.ParseFiles("web/templates/unpublished-articles.html")
		template.Must(tmpl, err).ExecuteTemplate(w, "page-content", al.Get())
	}
}

func ReviewArticle(al *data.ArticleList, s *data.CookieStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		uuid, err := uuid.Parse(r.PostFormValue("uuid"))
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		for _, article := range al.Get() {
			if article.UUID == uuid {
				tmpl, err := template.ParseFiles("web/templates/to-be-published.html")
				template.Must(tmpl, err).ExecuteTemplate(w, "page-content", article)
				return
			}
		}

		session, err := s.Get(r, "cookie")
		if err != nil {
			tmpl, err := template.ParseFiles("web/templates/login.html")
			msg := "Session nicht mehr gültig. Bitte erneut anmelden."
			template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
		}

		tmpl, err := template.ParseFiles("web/templates/hub.html")
		tmpl = template.Must(tmpl, err)
		tmpl.ExecuteTemplate(w, "page-content", session.Values["role"])
	}
}

func PublishArticle(c *data.Channel, al *data.ArticleList, s *data.CookieStore) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		uuid, err := uuid.Parse(r.PostFormValue("uuid"))
		if err != nil {
			log.Println(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		article, ok := al.Release(uuid)
		if !ok {
			// TODO: Warnung anzeigen
			// msg = "Alle Felder müssen ausgefüllt werden."
			// tmpl, err := template.ParseFiles("web/templates/add-user.html")
			// template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
			return
		}

		session, err := s.Get(r, "cookie")
		if err != nil {
			tmpl, err := template.ParseFiles("web/templates/login.html")
			msg := "Session nicht mehr gültig. Bitte erneut anmelden."
			template.Must(tmpl, err).ExecuteTemplate(w, "page-content", msg)
		}

		c.Add(&rss.Item{
			Title:       article.Title,
			Author:      session.Values["name"].(string),
			PubDate:     article.Created.Format(time.RFC1123Z),
			Description: article.Desc,
			Content:     &rss.Content{Value: article.Content},
			Categories:  article.Tags,
		})
		c.Save("tmp/rss.gob")

		tmpl, err := template.ParseFiles("web/templates/hub.html")
		tmpl = template.Must(tmpl, err)
		tmpl.ExecuteTemplate(w, "page-content", session.Values["role"])
	}
}