package main

import (
	"encoding/json"
	"fmt"
	"net/http"
	"strings"

	"github.com/gorilla/mux"
)

func handleApiUsersCall(w http.ResponseWriter, req *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	vars := mux.Vars(req)
	uid, uidok := vars["uid"]
	fn, fnok := vars["function"]
	switch req.Method {
	case "GET":
		if !uidok {
			handleApiListUsers(w)
			return
		}
		switch fn {
		case "byname":
			handleApiShowUserByName(uid, w)
		default:
			handleApiShowUser(uid, w)
		}

	case "POST", "PUT":
		if !uidok {
			userError(w)
			return
		}
		if !fnok {
			// Creating a new user
			var u *User
			var err error
			if u, err = m.GetUserByName(uid); err == nil {
				userError(w)
				return
			}
			u = NewUser(uid)
			m.SaveUser(u)
			m.LoadUsers()
			handleApiShowUser(u.Uuid, w)
			return
		}
		switch fn {
		case "slugs":
			slug, slugok := vars["slug"]
			if !slugok {
				userError(w)
				return
			}
			handleApiSubUser(uid, slug, w)

		default:
			userError(w)
			return
		}

	default:
		userError(w)
		return

	}
}

func handleApiListUsers(w http.ResponseWriter) {
	var res []byte
	var err error
	if res, err = json.Marshal(m.Users); err != nil {
		serverError(w)
		return
	}
	fmt.Fprint(w, string(res))
}

func handleApiShowUser(uid string, w http.ResponseWriter) {
	var err error
	var u *User
	if u, err = m.GetUser(uid); err != nil {
		userError(w)
		return
	}

	var res []byte
	if res, err = json.Marshal(u); err != nil {
		userError(w)
		return
	}
	fmt.Fprint(w, string(res))
	return
}

func handleApiShowUserByName(uname string, w http.ResponseWriter) {
	var err error
	var u *User
	if u, err = m.GetUserByName(uname); err != nil {
		userError(w)
		return
	}

	var res []byte
	if res, err = json.Marshal(u); err != nil {
		userError(w)
		return
	}
	fmt.Fprint(w, string(res))
	return
}

func handleApiSubUser(uid string, slug string, w http.ResponseWriter) {
	fmt.Println("Sub User", uid, slug)
	var u *User
	var err error
	if u, err = m.GetUser(uid); err != nil {
		userError(w)
		return
	}
	pts := strings.Split(slug, ";")
	if len(pts) != 2 {
		userError(w)
		return
	}
	//_, err = m.GetComic(pts[0], pts[1])
	if err != nil {
		userError(w)
		return
	}
	u.SubSlugs = append(u.SubSlugs, slug)
	err = m.SaveUser(u)
	if err != nil {
		userError(w)
		return
	}
	m.LoadUsers()
	handleApiShowUser(u.Uuid, w)
}
