package orm

import (
	"fmt"
	"net/http"

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

var (
	selectClassActivities = "SELECT * FROM activities WHERE class_id=?"

	selectUniqueClassTeachers = `
SELECT teachers.* FROM activities
INNER JOIN teachers on (teachers.id=activities.teacher_id OR teachers.id=activities.supply_teacher_id)
WHERE class_id=?
`
	selectClassStudents = "SELECT * FROM students WHERE class_id=?"
)

type Class struct {
	gorm.Model

	Name    string
	Alias   string
	Year    int
	Section string
	Field   string

	CoordinatorID uint `schema:"coordinator_id"`
	MinuterID     uint `schema:"minuter_id"`

	Coordinator *Teacher
	Minuter     *Teacher

	Teachers   []*Teacher
	Activities []*Activity
	Students   []*Student

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

func (t *Class) GetID() uint    { return t.ID }
func (c *Class) String() string { return c.Name }

func (c *Class) Create(args map[string]string, r *http.Request) (interface{}, error) {
	if r.Method == "GET" {
		class := new(Class)
		if err := DB().Find(&class.AllTeachers).Error; err != nil {
			return nil, err
		}
		return class, nil
	} else {
		class := new(Class)
		err := renderer.Decode(class, r)
		if err != nil {
			return nil, err
		}
		class, err = CreateClass(class)
		if err != nil {
			return nil, err
		}

		return class, nil
	}
}

func (c *Class) Read(args map[string]string, r *http.Request) (interface{}, error) {
	var class Class

	id := args["id"]

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

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

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

	return &class, nil
}

func (c *Class) ReadAll(args map[string]string, r *http.Request) (interface{}, error) {
	var classes []*Class
	if err := DB().Preload("Students").Preload("Coordinator").Preload("Minuter").Order("name").Find(&classes).Error; err != nil {
		return nil, err
	}
	for _, class := range classes {
		class.GetTeachers()
	}

	for _, class := range classes {
		class.GetStudents()
	}

	for _, class := range classes {
		class.GetActivities()
	}

	return classes, nil
}

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

		class := result.(*Class)

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

		class.SelectedMinuter = make(map[uint]string)
		class.SelectedMinuter[class.MinuterID] = "selected"

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

		return class, nil
	} else {
		class, err := c.Read(args, r)
		if err != nil {
			return nil, err
		}
		err = renderer.Decode(class, r)
		if err != nil {
			return nil, err
		}
		_, err = SaveClass(class)
		if err != nil {
			return nil, err
		}
		class, err = c.Read(args, r)
		if err != nil {
			return nil, err
		}
		return class.(*Class), nil
	}
}

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

func SaveClass(class interface{}) (interface{}, error) {
	if err := DB().Debug().Omit("Coordinator", "Minuter", "Teachers", "Activities", "Students").Save(class).Error; err != nil {
		return nil, err
	}
	return class, nil
}

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

func (c *Class) GetStudents() ([]*Student, error) {
	if err := DB().Raw(selectClassStudents, c.ID).Scan(&c.Students).Error; err != nil {
		return nil, err
	}
	return c.Students, nil
}

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

func CreateClass(class *Class) (*Class, error) {
	var classes []*Class
	if err := DB().Where("name=?", class.Name).Find(&classes).Error; err != nil {
		return nil, err
	}
	if len(classes) > 0 {
		return nil, fmt.Errorf("Class %s already exists!", class.Name)
	}
	if err := DB().Create(class).Error; err != nil {
		return nil, err
	}
	return class, nil
}
