package api

import (
	"../settings"
	"encoding/json"
	"net/http"
	"strconv"
	"strings"
)

var Groups = make(map[uint]Group)

func CreateGroup(w http.ResponseWriter, r *http.Request) {
	var newGroup Group
	err := json.NewDecoder(r.Body).Decode(&newGroup)
	if err != nil {
		json.NewEncoder(w).Encode(struct{ Error string }{Error: "error add new Group"})
		return
	}
	settings.DB.Create(&newGroup)
	json.NewEncoder(w).Encode(struct{ Result string }{Result: "added new Group"})
	return
}

func UpdateGroup(w http.ResponseWriter, r *http.Request) {
	var newGroup Group
	err := json.NewDecoder(r.Body).Decode(&newGroup)
	if err != nil {
		json.NewEncoder(w).Encode(struct{ Error string }{Error: "error update Group"})
		return
	}
	if _, ok := Groups[newGroup.ID]; !ok {
		json.NewEncoder(w).Encode(struct{ Error string }{Error: "error update Group"})
		return
	}
	Groups[newGroup.ID] = newGroup
	json.NewEncoder(w).Encode(struct{ Error string }{Error: "Successfully updated Group"})
	return
}

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

	if r.Method == "POST" {
		CreateGroup(w, r)
	}

	if r.Method == "UPDATE" || r.Method == "PATCH" {
		UpdateGroup(w, r)
	}

	path := replacePath(r.URL.Path, "/api/group/")

	if path == "" && r.Method == "GET"{
		GetGroups(w, r)
		return
	}

	if r.Method == "GET" {
		GetGroup(w, r)
		return
	}

	json.NewEncoder(w).Encode(struct{ Error string }{Error: "It is not GET method"})
}

func GetGroups(w http.ResponseWriter, r *http.Request){
	var output []Group
	settings.DB.Find(&output)
	json.NewEncoder(w).Encode(output)
}

func GetGroup(w http.ResponseWriter, r *http.Request) {
	path := replacePath(r.URL.Path, "/api/group/")
	num, err := strconv.Atoi(path)

	if err != nil || num < 0 {
		json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error"})
		return
	}

	var groups Group
	settings.DB.Where("id = ?", num).First(&groups)
	json.NewEncoder(w).Encode(groups)
	return
}

func GetGroupBySpecialty(w http.ResponseWriter, r *http.Request) {
	showAPIRequest(r)
	w.Header().Set("Content-Type", "application/json")
	if r.Method == "GET" {
		path := r.URL.Path
		path = strings.Replace(path, "/api/group/specialty/", "", 1)
		var output []Group

		num, err := strconv.Atoi(path)

		if err != nil || num < 0 {
			json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error"})
		}

		for _, group := range Groups {
			if group.IDSpecialty == uint(num) {
				output = append(output, group)
			}
		}
		json.NewEncoder(w).Encode(output)
	}
}
