package Api

import (
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"strconv"

	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Api/JsonSerialization"
	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Database"
	"git.tovijaeschke.xyz/tovi/SuddenImpactRecords/Models"
	"github.com/gorilla/mux"
)

func getPosts(w http.ResponseWriter, r *http.Request) {
	var (
		posts          []Models.Post
		returnJson     []byte
		values         url.Values
		page, pageSize int
		err            error
	)

	values = r.URL.Query()

	page, err = strconv.Atoi(values.Get("page"))
	if err != nil {
		log.Println("Could not parse page url argument")
		JsonReturn(w, 500, "An error occured")
		return
	}

	page, err = strconv.Atoi(values.Get("pageSize"))
	if err != nil {
		log.Println("Could not parse pageSize url argument")
		JsonReturn(w, 500, "An error occured")
		return
	}

	posts, err = Database.GetPosts(page, pageSize)
	if err != nil {
		log.Printf("An error occured: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	returnJson, err = json.MarshalIndent(posts, "", "  ")
	if err != nil {
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
	w.Write(returnJson)
}

func getFrontPagePosts(w http.ResponseWriter, r *http.Request) {
	var (
		posts      []Models.Post
		returnJson []byte
		err        error
	)

	posts, err = Database.GetFrontPagePosts()
	if err != nil {
		log.Printf("An error occured: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	returnJson, err = json.MarshalIndent(posts, "", "  ")
	if err != nil {
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
	w.Write(returnJson)
}

func getPost(w http.ResponseWriter, r *http.Request) {
	var (
		postData   Models.Post
		returnJson []byte
		err        error
	)

	postData, err = getPostById(w, r)
	if err != nil {
		return
	}

	returnJson, err = json.MarshalIndent(postData, "", "  ")
	if err != nil {
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
	w.Write(returnJson)
}

func createPost(w http.ResponseWriter, r *http.Request) {
	var (
		requestBody []byte
		postData    Models.Post
		returnJson  []byte
		err         error
	)

	// TODO: Add auth

	log.Printf("Posts handler recieved %s request", r.Method)

	requestBody, err = ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("Error encountered reading POST body: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	postData, err = JsonSerialization.DeserializePost(requestBody, []string{
		"id",
		"links",
		"images",
		"videos",
		"audios",
	}, false)
	if err != nil {
		log.Printf("Invalid data provided to posts API: %s\n", err.Error())
		JsonReturn(w, 405, "Invalid data")
		return
	}

	err = Database.CreatePost(&postData)
	if err != nil {
		JsonReturn(w, 405, "Invalid data")
	}

	returnJson, err = json.MarshalIndent(postData, "", "  ")
	if err != nil {
		log.Printf("An error occured: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
	w.Write(returnJson)
}

func updatePost(w http.ResponseWriter, r *http.Request) {
	var (
		postData    Models.Post
		requestBody []byte
		returnJson  []byte
		urlVars     map[string]string
		id          string
		ok          bool
		err         error
	)

	urlVars = mux.Vars(r)
	id, ok = urlVars["postID"]
	if !ok {
		log.Printf("Error encountered getting id\n")
		JsonReturn(w, 500, "An error occured")
		return
	}

	requestBody, err = ioutil.ReadAll(r.Body)
	if err != nil {
		log.Printf("Error encountered reading POST body: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	postData, err = JsonSerialization.DeserializePost(requestBody, []string{}, true)
	if err != nil {
		log.Printf("Invalid data provided to posts API: %s\n", err.Error())
		JsonReturn(w, 405, "Invalid data")
		return
	}

	postData, err = Database.UpdatePost(id, &postData)
	if err != nil {
		log.Printf("An error occured: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	returnJson, err = json.MarshalIndent(postData, "", "  ")
	if err != nil {
		log.Printf("An error occured: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
	w.Write(returnJson)
}

func deletePost(w http.ResponseWriter, r *http.Request) {
	var (
		postData Models.Post
		err      error
	)

	postData, err = getPostById(w, r)
	if err != nil {
		return
	}

	err = Database.DeletePost(&postData)
	if err != nil {
		log.Printf("An error occured: %s\n", err.Error())
		JsonReturn(w, 500, "An error occured")
		return
	}

	// Return updated json
	w.WriteHeader(http.StatusOK)
}
