package orm

import (
	"net/http"

	"github.com/jinzhu/gorm"
	"gogs.carducci-dante.gov.it/karmen/core/renderer"
)

type Department struct {
	gorm.Model
	Name string

	CoordinatorID uint `schema:"coordinator_id"`
	Coordinator   Teacher

	Subjects []*Subject
	Teachers []*Teacher
}

type DepartmentForUpdate struct {
	Department          Department
	AllTeachers         []*Teacher
	SelectedCoordinator map[uint]string
	SelectedMinuter     map[uint]string
}

type DepartmentForAdd struct {
	AllTeachers []*Teacher
}

var (
	selectUniqueDepartmentTeachers = `
SELECT DISTINCT teachers.* FROM subjects 
INNER JOIN activities ON activities.subject_id=subjects.id 
INNER JOIN teachers ON activities.teacher_id=teachers.id 
WHERE department_id=?`

	selectUniqueDepartmentSubjects = `
SELECT * FROM subjects
WHERE department_id=?`
)

func (d *Department) GetID() uint { return d.ID }

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

func GetDepartmentAll(args map[string]string) (interface{}, error) {
	var department Department

	id := args["id"]

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

	if err := DB().Raw(selectUniqueDepartmentTeachers, id).Scan(&department.Teachers).Error; err != nil {
		return nil, err
	}

	if err := DB().Raw(selectUniqueDepartmentSubjects, id).Scan(&department.Subjects).Error; err != nil {
		return nil, err
	}

	if department.CoordinatorID != 0 {
		if !DB().First(&department.Coordinator, department.CoordinatorID).RecordNotFound() {
			if err := DB().First(&department.Coordinator, department.CoordinatorID).Error; err != nil {
				return nil, err
			}
		}
	}

	return &department, nil
}

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

func GetDepartmentsAll(args map[string]string) (interface{}, error) {
	var departments []*Department
	if err := DB().Preload("Coordinator").Order("name").Find(&departments).Error; err != nil {
		return nil, err
	}
	for _, department := range departments {
		department.GetTeachers()
	}
	for _, department := range departments {
		department.GetSubjects()
	}
	return departments, nil
}

func SaveDepartment(department interface{}) (interface{}, error) {
	if err := DB().Omit("Teachers", "Subjects").Save(department).Error; err != nil {
		return nil, err
	}
	return department, nil
}

func UpdateDepartment(args map[string]string, r *http.Request) (IDer, error) {
	department, err := GetDepartment(args)
	if err != nil {
		return nil, err
	}
	err = renderer.Decode(department, r)
	if err != nil {
		return nil, err
	}
	_, err = SaveDepartment(department)
	if err != nil {
		return nil, err
	}
	department, err = GetDepartment(args)
	if err != nil {
		return nil, err
	}
	return department.(*Department), nil
}

func AddDepartment(args map[string]string, r *http.Request) (IDer, error) {
	department := new(Department)
	err := renderer.Decode(department, r)
	if err != nil {
		return nil, err
	}
	department, err = CreateDepartment(department)
	if err != nil {
		return nil, err
	}

	return department, nil
}

func CreateDepartment(department *Department) (*Department, error) {
	if err := DB().Create(department).Error; err != nil {
		return nil, err
	}
	return department, nil
}

func DeleteDepartment(args map[string]string, r *http.Request) (IDer, error) {
	department, err := GetDepartment(args)
	if err != nil {
		return nil, err
	}
	if err := DB().Unscoped().Delete(department.(*Department)).Error; err != nil {
		return nil, err
	}
	return department.(*Department), nil
}

func GetDepartmentForAdd(args map[string]string) (interface{}, error) {
	var data DepartmentForAdd

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

	return data, nil
}

func GetDepartmentForUpdate(args map[string]string) (interface{}, error) {
	var data DepartmentForUpdate

	id := args["id"]

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

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

	data.SelectedCoordinator = make(map[uint]string)
	data.SelectedCoordinator[data.Department.CoordinatorID] = "selected"

	return data, nil
}

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

func (t *Department) GetSubjects() ([]*Subject, error) {
	if err := DB().Raw(selectUniqueDepartmentSubjects, t.ID).Scan(&t.Subjects).Error; err != nil {
		return nil, err
	}
	return t.Subjects, nil
}
