package orm

import (
	"fmt"
	"net/http"

	"gogs.carducci-dante.gov.it/karmen/core/renderer"
)

type Student struct {
	Credential

	Handicap bool `schema:"Handicap" sql:"default: false"`
	DSA      bool `schema:"DSA" sql:"default: false"`
	BES      bool `schema:"BES" sql:"default: false"`

	TutorID uint `schema:"tutor_id"`
	ClassID uint `schema:"class_id"`

	Class      *Class
	Tutor      *Teacher
	Teachers   []*Teacher
	Activities []*Activity
}

type StudentForUpdate struct {
	Student     Student
	AllClasses  []*Class
	AllTeachers []*Teacher

	SelectedClass   map[uint]string
	SelectedTeacher map[uint]string
}

type StudentForAdd struct {
	AllClasses  []*Class
	AllTeachers []*Teacher
}

var (
	selectStudentTeachers = `
SELECT teachers.* FROM activities
INNER JOIN teachers ON (activities.teacher_id=teachers.id OR activities.supply_teacher_id=teachers.id) 
WHERE student_id=?
`
)

func (s *Student) GetID() uint { return s.ID }

func GetStudent(args map[string]string) (interface{}, error) {
	var student Student
	if err := DB().First(&student, args["id"]).Error; err != nil {
		return nil, err
	}
	return &student, nil
}

func GetStudentAll(args map[string]string) (interface{}, error) {
	var student Student

	id := args["id"]

	if err := DB().Preload("Class").Preload("Class.Coordinator").Where("id = ?", id).Find(&student).Error; err != nil {
		return nil, err
	}

	if err := DB().Preload("Subject").Preload("Teacher").Preload("Class").Where("student_id=?", id).Find(&student.Activities).Error; err != nil {
		return nil, err
	}

	return &student, nil
}

func GetStudents(args map[string]string) (interface{}, error) {
	var students []*Student
	if err := DB().Order("surname,name").Find(&students).Error; err != nil {
		return nil, err
	}
	return students, nil
}

func GetStudentsFast(args map[string]string) (interface{}, error) {
	var students []*Student
	if err := DB().Preload("Class").Order("surname,name").Find(&students).Error; err != nil {
		return nil, err
	}
	return students, nil
}

func GetStudentsAll(args map[string]string) (interface{}, error) {
	var students []*Student
	if err := DB().Preload("Class").Preload("Class.Coordinator").Preload("Tutor").Order("surname,name").Find(&students).Error; err != nil {
		return nil, err
	}
	for _, student := range students {
		student.GetTeachers()
	}
	for _, student := range students {
		student.GetActivities()
	}
	return students, nil
}

func SaveStudent(student interface{}) (interface{}, error) {
	if err := DB().Omit("Class", "Tutor", "Teachers", "Activities").Save(student).Error; err != nil {
		return nil, err
	}
	return student, nil
}

func UpdateStudent(args map[string]string, r *http.Request) (IDer, error) {
	student, err := GetStudent(args)
	if err != nil {
		return nil, err
	}

	// FIXME: Should not be hard set.
	student.(*Student).Handicap = false
	student.(*Student).DSA = false
	student.(*Student).BES = false

	err = renderer.Decode(student, r)
	if err != nil {
		return nil, err
	}

	_, err = SaveStudent(student)
	if err != nil {
		return nil, err
	}
	student, err = GetStudent(args)
	if err != nil {
		return nil, err
	}
	return student.(*Student), nil
}

func AddStudent(args map[string]string, r *http.Request) (IDer, error) {
	student := new(Student)
	err := renderer.Decode(student, r)
	if err != nil {
		return nil, err
	}
	student, err = CreateStudent(student)
	if err != nil {
		return nil, err
	}

	return student, nil
}

func CreateStudent(student *Student) (*Student, error) {
	if err := DB().Create(student).Error; err != nil {
		return nil, err
	}
	return student, nil
}

func DeleteStudent(args map[string]string, r *http.Request) (IDer, error) {
	student, err := GetStudent(args)
	if err != nil {
		return nil, err
	}
	if err := DB().Unscoped().Delete(student.(*Student)).Error; err != nil {
		return nil, err
	}
	return student.(*Student), nil
}

func GetStudentForUpdate(args map[string]string) (interface{}, error) {
	var data StudentForUpdate

	id := args["id"]

	if err := DB().Preload("Class").First(&data.Student, id).Error; err != nil {
		return nil, err
	}

	if err := DB().Find(&data.AllClasses).Error; err != nil {
		return nil, err
	}

	if err := DB().Find(&data.AllTeachers).Error; err != nil {
		return nil, err
	}

	data.SelectedClass = make(map[uint]string)
	data.SelectedClass[data.Student.ClassID] = "selected"

	data.SelectedTeacher = make(map[uint]string)
	data.SelectedTeacher[data.Student.TutorID] = "selected"

	return data, nil
}

func GetStudentForAdd(args map[string]string) (interface{}, error) {
	var data StudentForAdd

	if err := DB().Find(&data.AllClasses).Error; err != nil {
		return nil, err
	}

	if err := DB().Find(&data.AllTeachers).Error; err != nil {
		return nil, err
	}

	return data, nil
}

func (s *Student) GetTeachers() ([]*Teacher, error) {
	if err := DB().Raw(selectStudentTeachers, s.ID).Scan(&s.Teachers).Error; err != nil {
		return nil, err
	}
	return s.Teachers, nil
}

func (s *Student) GetActivities() ([]*Activity, error) {
	if err := DB().Preload("Student").Preload("Subject").Preload("Class").Where("student_id=?", s.ID).Find(&s.Activities).Error; err != nil {
		return nil, err
	}
	return s.Activities, nil
}

func (s *Student) CompleteName() string {
	return fmt.Sprintf("%s %s", s.Name, s.Surname)
}
