package main

import (
	"bytes"
	"net/http"
	"strings"
	"time"
)

func (app *application) home(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	path := strings.Split(r.URL.Path, "/")
	if path[1] != "" {
		app.notFound(w)
	} else {
		/* 		p, err := app.aggregate("html/projects")
		   		if err != nil {
		   			app.serverError(w, err)
		   		} */

		err := renderPage(w, "index")
		if err != nil {
			app.serverError(w, err)
		}
	}
}

func (app *application) page(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	path := strings.Split(r.URL.Path, "/")

	// Redirect paths like /about/sth/oeusth to /about
	if len(path) > 2 {
		http.Redirect(w, r, "/"+path[1], http.StatusFound)
	}

	err := renderPage(w, path[1])
	if err != nil {
		app.serverError(w, err)
	}
}

func (app *application) blog(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	path := strings.Split(r.URL.Path, "/")

	// Setup redirects for trailing / and extraneous path elements
	if len(path) > 3 {
		// Redirect to /blog/article
		http.Redirect(w, r, "/"+path[1]+"/"+path[2], http.StatusFound)
	} else if len(path) == 3 && path[2] == "" {
		// Redirect to /blog
		http.Redirect(w, r, "/"+path[1], http.StatusFound)
	} else if len(path) == 2 {
		p, err := app.aggregate("html/blog")
		if err != nil {
			app.serverError(w, err)
			return
		}
		a, err := app.aggregate("html/archive")
		if err != nil {
			app.serverError(w, err)
			return
		}

		err = renderBlog(w, "blog2", p, a)
		if err != nil {
			app.serverError(w, err)
			return
		}
	} else if len(path) == 3 {
		if !app.fileExists("html/" + path[1] + "/" + path[2] + ".tmpl.html") {
			app.notFound(w)
			return
		}
		post := app.parseFileName(path[2])

		err := renderPost(w, path[2], post)
		if err != nil {
			app.serverError(w, err)
		}
	}
}

func (app *application) archive(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")

	path := strings.Split(r.URL.Path, "/")

	// Setup redirects for trailing / and extraneous path elements
	if len(path) > 3 {
		// Redirect to /archive/article
		http.Redirect(w, r, "/"+path[1]+"/"+path[2], http.StatusFound)
	} else if len(path) == 3 && path[2] == "" {
		// Redirect to /blog
		http.Redirect(w, r, "/blog", http.StatusFound)
	} else if len(path) == 3 {
		if !app.fileExists("html/" + path[1] + "/" + path[2] + ".tmpl.html") {
			app.notFound(w)
			return
		}
		post := app.parseFileName(path[2])

		err := renderArchivePost(w, path[2], post)
		if err != nil {
			app.serverError(w, err)
		}
	}
}

func (app application) feed(w http.ResponseWriter, r *http.Request) {
	p, err := app.aggregate("html/blog")
	if err != nil {
		app.serverError(w, err)
	}
	w.Header().Set("Content-Type", "application/atom+xml")
	feed := bytes.NewReader(generateFeed(r.Host, p))
	http.ServeContent(w, r, "atom.xml", time.Now(), feed)
}