//Calendar implementation for the HTWK Leipzig timetable. Evaluation and display of the individual dates in iCal format.
//Copyright (C) 2024 HTWKalender support@htwkalender.de

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Affero General Public License for more details.

//You should have received a copy of the GNU Affero General Public License
//along with this program.  If not, see <https://www.gnu.org/licenses/>.

package db

import (
	"github.com/pocketbase/dbx"
	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/core"
	"htwkalender/data-manager/model"
	"log/slog"
)

type SeminarGroup struct {
	University    string `db:"university" json:"university"`
	GroupShortcut string `db:"shortcut" json:"shortcut"`
	GroupId       string `db:"groupId" json:"groupId"`
	Course        string `db:"course" json:"course"`
	Faculty       string `db:"faculty" json:"faculty"`
	FacultyId     string `db:"facultyId" json:"facultyId"`
	Semester      string `db:"semester" json:"semester"`
	core.BaseModel
}

func (s *SeminarGroup) TableName() string {
	return "groups"
}

// UniqueKey Should be same as unique constraint in the database
func (s *SeminarGroup) UniqueKey() string {
	return s.Course + s.Semester
}

func (s *SeminarGroup) toSeminarGroupModel() model.SeminarGroup {
	return model.SeminarGroup{
		University:    s.University,
		GroupShortcut: s.GroupShortcut,
		GroupId:       s.GroupId,
		Course:        s.Course,
		Faculty:       s.Faculty,
		FacultyId:     s.FacultyId,
		Semester:      s.Semester,
	}
}

func (s *SeminarGroups) toSeminarGroupModels() []model.SeminarGroup {
	var seminarGroups []model.SeminarGroup
	for _, group := range *s {
		seminarGroups = append(seminarGroups, group.toSeminarGroupModel())
	}
	return seminarGroups
}

type SeminarGroups []*SeminarGroup

func SaveGroups(seminarGroups SeminarGroups, app *pocketbase.PocketBase) (SeminarGroups, error) {

	// delete all groups from the database
	execute, err := app.DB().Delete("groups", dbx.NewExp("1 = 1")).Execute()
	if err != nil {
		return nil, err
	}
	rowCount, _ := execute.RowsAffected()

	savedGroups := SeminarGroups{}
	for _, group := range seminarGroups {
		saveErr := app.Save(group)
		if saveErr != nil {
			return nil, saveErr
		}
		savedGroups = append(savedGroups, group)
	}
	slog.Info("Saved all groups to the database", "insert", len(savedGroups), "deleted", rowCount)

	return savedGroups, nil
}

func GetAllCourses(app *pocketbase.PocketBase) []string {

	var courses []struct {
		CourseShortcut string `db:"course" json:"course"`
	}

	// get all rooms from event records in the events collection
	err := app.DB().Select("course").From("groups").All(&courses)
	if err != nil {
		slog.Error("Error while getting groups from database: ", "error", err)
		return []string{}
	}

	var courseArray []string

	for _, course := range courses {
		courseArray = append(courseArray, course.CourseShortcut)
	}

	return courseArray
}

func GetAllCoursesForSemester(app *pocketbase.PocketBase, semester string) []model.SeminarGroup {

	var courses SeminarGroups

	// get all courses for a specific semester
	err := app.DB().Select("*").From("groups").Where(dbx.NewExp("semester = {:semester}", dbx.Params{"semester": semester})).All(&courses)
	if err != nil {
		slog.Error("Error while getting groups from database: ", "error", err)
		return nil
	}

	return courses.toSeminarGroupModels()

}

func GetAllCoursesForSemesterWithEvents(app *pocketbase.PocketBase, semester string) ([]string, error) {

	var courses []struct {
		CourseShortcut string `db:"course" json:"course"`
	}

	// get all courses from events distinct for a specific semester
	err := app.DB().Select("course").From("events").Where(dbx.NewExp("semester = {:semester}", dbx.Params{"semester": semester})).Distinct(true).All(&courses)
	if err != nil {
		slog.Error("Error while getting groups from database: ", "error", err)
		return nil, err
	}

	var courseArray []string

	for _, course := range courses {
		courseArray = append(courseArray, course.CourseShortcut)
	}

	return courseArray, nil
}

func FindCourseByCourseName(app *pocketbase.PocketBase, courseName string) (model.SeminarGroup, error) {

	var course SeminarGroup

	// get the course by its name
	err := app.DB().Select("*").From("groups").Where(dbx.NewExp("course = {:course}", dbx.Params{"course": courseName})).One(&course)
	if err != nil {
		slog.Error("Error while getting group from database: ", "error", err)
		return model.SeminarGroup{}, err
	}

	return course.toSeminarGroupModel(), nil
}
