package orm

import (
	"net/http"

	"github.com/jinzhu/gorm"
	"gogs.carduccidante.edu.it/karmen/core/renderer"
)

type Department struct {
	gorm.Model
	Name string

	CoordinatorID uint `schema:"coordinator_id"`
	Coordinator   *Teacher

	Subjects []*Subject
	Teachers []*Teacher

	AllTeachers         []*Teacher      `gorm:"-"`
	SelectedCoordinator map[uint]string `gorm:"-"`
}

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 OR teachers.id=activities.supply_teacher_id)
WHERE department_id=?`

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

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

func (d *Department) String() string {
	return d.Name
}

func (d *Department) Create(args map[string]string, r *http.Request) (interface{}, error) {
	if r.Method == "GET" {
		department := new(Department)
		if err := DB().Find(&department.AllTeachers).Error; err != nil {
			return nil, err
		}
		return department, nil
	} else {
		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 (d *Department) Read(args map[string]string, r *http.Request) (interface{}, error) {
	var department Department

	id := args["id"]

	if err := DB().Preload("Coordinator").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
	}

	return &department, nil
}

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

func (d *Department) Update(args map[string]string, r *http.Request) (interface{}, error) {
	if r.Method == "GET" {
		result, err := d.Read(args, r)
		if err != nil {
			return nil, err
		}

		department := result.(*Department)

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

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

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

		return department.(*Department), nil
	}
}

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

func SaveDepartment(department interface{}) (interface{}, error) {
	if err := DB().Debug().Omit("Coordinator", "Teachers", "Subjects").Save(department).Error; err != nil {
		return nil, err
	}
	return 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 (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
}
