package api

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

var studyplan []Studyplan


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

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

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

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

	if path == "" {
		GetStudyPlan(w, r)
		return
	}

	if path != "" && strings.HasPrefix(path, "variative/") {
    	path = replacePath(r.URL.Path, "/api/studyplan/variative/")
    	groupnum, err := strconv.Atoi(path)
	 	if err != nil {
	 	json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error2"})
	 	fmt.Println(err)
	 	return
		}
    	VariativeHoursByGroup(w, r, groupnum)
    } else {
		path = replacePath(r.URL.Path, "/api/studyplan/")
		num, err := strconv.Atoi(path)
		if err != nil {
			json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error1"})
			fmt.Println(err)
			return
		}
    
		settings.DB.Find(&studyplan)
		if num < 0 || num > len(studyplan)+1 {
			json.NewEncoder(w).Encode(struct{ Error string }{Error: "strconv error3"})
			fmt.Println(err)
			return
		}
		
		if r.Method == "GET" {
		GetStudyPlanById(w, r, num)
		return
		}
		json.NewEncoder(w).Encode(struct{ Error string }{Error: "This method is not supported"})
    }
			
}

func UpdateStudyPlan(w http.ResponseWriter, r *http.Request) {
	var StudyPlan Studyplan
	var StudyplanToUpdate Studyplan
	err := json.NewDecoder(r.Body).Decode(&StudyPlan)

	if err != nil {
		showError(r, err)
		json.NewEncoder(w).Encode(struct{ Error string }{Error: "error update StudyPlan"})
		return
	}
	settings.DB.First(&StudyplanToUpdate, StudyPlan.ID)
	settings.DB.Model(&StudyplanToUpdate).Updates(StudyPlan)
	json.NewEncoder(w).Encode(struct{ Result string }{Result: "updated StudyPlan"})
	return
}

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

func GetStudyPlanById(w http.ResponseWriter, r *http.Request, num int) {
	var StudyPlan Studyplan
	settings.DB.Where("id = ?", num).First(&StudyPlan)
	json.NewEncoder(w).Encode(StudyPlan)
	return
}

func GetStudyPlan(w http.ResponseWriter, r *http.Request) {
	showAPIRequest(r)
	w.Header().Set("Content-Type", "application/json")
	if r.Method == "GET" {
		var StudyPlan []Studyplan
		settings.DB.Find(&StudyPlan)
		json.NewEncoder(w).Encode(StudyPlan)
	}
	return
}

func VariativeHoursByGroup(w http.ResponseWriter, r *http.Request, groupnum int) {
	var group Group
	var StudyPlan Studyplan
	var ExampleProgram Exampleprogram
	var SubjectOfPlan []Subjectofplan
	var opop []Subjectofexample
	
	// ишем id группы по ее номеру
	settings.DB.Where("groupnumber = ?", groupnum).First(&group)
	// нашли план обучения групы
	 settings.DB.Where("id_group = ?", group.ID).First(&StudyPlan)
	// // все предметы группы в ОПОП
	 settings.DB.Where("id_specialty = ?", StudyPlan.IDSpecialty).First(&ExampleProgram)
	 settings.DB.Where("id_exampleprogram = ?", ExampleProgram.ID).Find(&opop)
	// // все предметы группы не в ОПОП
	 settings.DB.Where("id_plan = ?", StudyPlan.ID).Find(&SubjectOfPlan)
	
	var vh VariateHours
	var Variatehours []VariateHours
	// //Вот тут ваще хз, проверь плез
	  for i := range opop {
	  	for j := range SubjectOfPlan {
	  		//fmt.Println(opop[i].Totalhours, " -----> ",SubjectOfPlan[j].Hoursquantitytotal )
	  		if opop[i].IDSubject == SubjectOfPlan[j].IDSubject {
	 			//fmt.Println(opop[i].Totalhours, " -----> ",SubjectOfPlan[j].Hoursquantitytotal, "Sovpodaet" )
	  			Freehours1 :=  opop[i].Totalhours - SubjectOfPlan[j].Hoursquantitytotal
	  			IDSubject1 := opop[i].IDSubject
	  			//fmt.Println(IDSubject1, " -----> IDSubject ",Freehours1, "-----> Freehours" )
	  			vh = VariateHours{ IDSubject: IDSubject1, Freehours: Freehours1}
	  			Variatehours= append(Variatehours, vh)
	  			}
	  		}
	  	}
	
	json.NewEncoder(w).Encode(Variatehours) 
	return
	}
