package orm

import (
	"fmt"
	"net/http"

	"gogs.carduccidante.edu.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"`

	Handicap bool
	DSA      bool
	BES      bool

	FatherLastname  string
	FatherFirstname string
	FatherEmail     string

	MotherLastname  string
	MotherFirstname string
	MotherEmail     string

	LegalGuardianLastname  string
	LegalGuardianFirstname string
	LegalGuardianEmail     string

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

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

	AllClasses  []*Class   `gorm:"-"`
	AllTeachers []*Teacher `gorm:"-"`

	SelectedClass   map[uint]string `gorm:"-"`
	SelectedTeacher map[uint]string `gorm:"-"`
}

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 (s *Student) String() string { return s.CompleteName() }

func (s *Student) Create(args map[string]string, r *http.Request) (interface{}, error) {
	if r.Method == "GET" {
		student := new(Student)
		if err := DB().Find(&student.AllTeachers).Error; err != nil {
			return nil, err
		}
		if err := DB().Find(&student.AllClasses).Error; err != nil {
			return nil, err
		}

		return student, nil
	} else {
		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 (s *Student) Read(args map[string]string, r *http.Request) (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 (s *Student) ReadAll(args map[string]string, r *http.Request) (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 (s *Student) Update(args map[string]string, r *http.Request) (interface{}, error) {
	if r.Method == "GET" {
		result, err := s.Read(args, r)
		if err != nil {
			return nil, err
		}

		student := result.(*Student)

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

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

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

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

		return student, nil
	} else {
		student, err := s.Read(args, r)
		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 = s.Read(args, r)
		if err != nil {
			return nil, err
		}

		return student.(*Student), nil
	}
}

func (s *Student) Delete(args map[string]string, r *http.Request) (interface{}, error) {
	student, err := s.Read(args, r)
	if err != nil {
		return nil, err
	}
	if err := DB().Unscoped().Delete(student.(*Student)).Error; err != nil {
		return nil, err
	}
	return student.(*Student), 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 CreateStudent(student *Student) (*Student, error) {
	if err := DB().Create(student).Error; err != nil {
		return nil, err
	}
	return student, 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)
}
