package api

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



func CardOfGroupRoute(w http.ResponseWriter, r *http.Request) {

	showAPIRequest(r)
	w.Header().Set("Content-Type", "application/json")

	path := replacePath(r.URL.Path, "/api/cardofgroup/")
	var groupnum1 string
	var semesternum1 string
	
	if path != "" && strings.Contains(path, "semester/") && r.Method == "GET" {
		// парсим для нахождения номера группы и семестра
		list := strings.Split(path, "/semester/")
		groupnum1 = list[0]
		semesternum1 = list[1]
		
		// преобразовывает в int
		groupnum, err := strconv.Atoi(groupnum1)
	  	if err != nil {
	  	json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error1"})
	  	fmt.Println(err)
	  	return
	 	}
	 	semesternum, err := strconv.Atoi(semesternum1)
	  	if err != nil {
	  	json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error2"})
	  	fmt.Println(err)
	  	return
	 	}

	 	GetCardOfGroup(w, r, groupnum, semesternum)
	 	return
	}

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

func GetCardOfGroup(w http.ResponseWriter, r *http.Request,groupnum int ,semesternum int) {
 	var semester Semester
 	var group Group
 	var subjectofgroup []Subjectofgroup

 	settings.DB.Where("id = ?", semesternum).First(&semester)
	settings.DB.Where("groupnumber = ?", groupnum).First(&group)
	settings.DB.Where("id_group = ? AND  id_semester = ?", group.ID, semester.ID).Find(&subjectofgroup)


 	json.NewEncoder(w).Encode(subjectofgroup)
 	
 	return
}
