package api

import (
	"encoding/json"
	"fmt"
	"html/template"
	"io/ioutil"
	"log"
	"net/http"
	"sort"
	"strings"

	"github.com/gorilla/mux"
	"github.com/gorilla/schema"

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

var (
	selectClassActivities = `
SELECT activities.id AS activity_id,teachers.name,teachers.surname,subjects.name AS subject,activities.hours FROM activities 
INNER JOIN teachers ON teachers.id=activities.teacher_id 
INNER JOIN subjects ON subjects.id=activities.subject_id 
WHERE class_id=? AND activities.deleted_at IS NULL `

	selectUniqueClassTeachers = `
SELECT surname FROM (SELECT activities.id as activity_id,teachers.name,teachers.surname,subjects.name as subject,activities.hours from activities 
inner join teachers on teachers.id=activities.teacher_id 
inner join subjects on subjects.id=activities.subject_id 
where class_id=?) as activities GROUP BY surname`
)

func classesHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var classes []*orm.Class

		if err := orm.DB().Find(&classes).Error; err != nil {
			panic(err)
		}

		for _, class := range classes {
			orm.DB().Raw(selectUniqueClassTeachers, class.ID).Scan(&class.Teachers)
		}

		sort.Slice(classes, func(i, j int) bool {
			return strings.ToLower(classes[i].Name) < strings.ToLower(classes[j].Name)
		})
		if err := renderer.Render(w, "base", "classes", classes); err != nil {
			panic(err)
		}
	}
	return http.HandlerFunc(fn)
}

func classesShowHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {

		type teacherActivity struct {
			ActivityID int
			Name       string
			Surname    string
			Subject    string
			Hours      int
		}

		var data struct {
			Class             orm.Class
			TeacherActivities []teacherActivity
		}
		if err := orm.DB().First(&data.Class, mux.Vars(r)["id"]).Error; err != nil {
			panic(err)
		}

		orm.DB().Raw(selectClassActivities, mux.Vars(r)["id"]).Scan(&data.TeacherActivities)

		sort.Slice(data.TeacherActivities, func(i, j int) bool {
			return strings.ToLower(data.TeacherActivities[i].Surname) < strings.ToLower(data.TeacherActivities[j].Surname)
		})

		if data.Class.CoordinatorID != 0 {
			if !orm.DB().First(&data.Class.Coordinator, data.Class.CoordinatorID).RecordNotFound() {
				if err := orm.DB().First(&data.Class.Coordinator, data.Class.CoordinatorID).Error; err != nil {
					panic(err)
				}
			}
		}

		if data.Class.MinuterID != 0 {
			if !orm.DB().First(&data.Class.Minuter, data.Class.MinuterID).RecordNotFound() {
				if err := orm.DB().First(&data.Class.Minuter, data.Class.MinuterID).Error; err != nil {
					panic(err)
				}
			}
		}

		if err := renderer.Render(w, "base", "classes_show", data); err != nil {
			panic(err)
		}
	}
	return http.HandlerFunc(fn)
}

func classesAddHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			var data struct {
				Update    bool
				Teachers  []orm.Teacher
				SubmitUrl template.URL
			}
			data.SubmitUrl = template.URL(fmt.Sprintf("/classes/add"))

			if err := orm.DB().Find(&data.Teachers).Error; err != nil {
				panic(err)
			}

			if err := renderer.Render(w, "base", "classes_add_update", data); err != nil {
				panic(err)
			}
		} else if r.Method == "POST" {
			var class orm.Class
			if err := r.ParseForm(); err != nil {
				panic(err)
			}

			decoder := schema.NewDecoder()
			if err := decoder.Decode(&class, r.PostForm); err != nil {
				panic(err)
			}

			orm.DB().NewRecord(class)

			if err := orm.DB().Create(&class).Error; err != nil {
				panic(err)
			}

			http.Redirect(w, r, fmt.Sprintf("/classes/%d", class.ID), http.StatusSeeOther)
		}

	}
	return http.HandlerFunc(fn)
}

func classesDeleteHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var class orm.Class
		if err := orm.DB().First(&class, mux.Vars(r)["id"]).Error; err != nil {
			panic(err)
		}

		if err := orm.DB().Delete(&class).Error; err != nil {
			panic(err)
		}

		var data struct {
			RedirectUrl string `json:"redirect_url"`
		}

		data.RedirectUrl = "/classes"

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)
	}
	return http.HandlerFunc(fn)
}

func classesUpdateHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			var data struct {
				Update              bool
				SubmitUrl           template.URL
				Class               orm.Class
				Teachers            []orm.Teacher
				SelectedCoordinator map[uint]string
				SelectedMinuter     map[uint]string
			}

			if err := orm.DB().First(&data.Class, mux.Vars(r)["id"]).Error; err != nil {
				panic(err)
			}

			if err := orm.DB().Find(&data.Teachers).Error; err != nil {
				panic(err)
			}

			log.Println("Coordinator ID", data.Class.CoordinatorID)

			if id := data.Class.CoordinatorID; id != 0 {
				data.SelectedCoordinator = make(map[uint]string)
				data.SelectedCoordinator[id] = "selected"
			}

			if id := data.Class.MinuterID; id != 0 {
				data.SelectedMinuter = make(map[uint]string)
				data.SelectedMinuter[id] = "selected"
			}

			data.Update = true
			data.SubmitUrl = template.URL(fmt.Sprintf("/classes/%d/update", data.Class.ID))

			if err := renderer.Render(w, "base", "classes_add_update", data); err != nil {
				panic(err)
			}
		} else if r.Method == "POST" {
			var class orm.Class

			if err := orm.DB().First(&class, mux.Vars(r)["id"]).Error; err != nil {
				panic(err)
			}

			if err := r.ParseForm(); err != nil {
				panic(err)
			}

			decoder := schema.NewDecoder()
			if err := decoder.Decode(&class, r.PostForm); err != nil {
				panic(err)
			}

			if err := orm.DB().Save(&class).Error; err != nil {
				panic(err)
			}

			http.Redirect(w, r, fmt.Sprintf("/classes/%d", class.ID), http.StatusSeeOther)
		}

	}
	return http.HandlerFunc(fn)
}

func classesImportHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		r.ParseMultipartForm(32 << 20)
		file, _, err := r.FormFile("classes_import")
		if err != nil {
			panic(err)
		}
		defer file.Close()
		data, err := ioutil.ReadAll(file)
		if err != nil {
			panic(err)
		}
		if importer, err := edt.NewImporter(
			string(data),
			map[string]string{
				"NOME": "name",
			},
		); err != nil {
			panic(err)
		} else {
			if err := orm.Import(&orm.Class{}, importer); err != nil {
				panic(err)
			}
			http.Redirect(w, r, "/classes", http.StatusSeeOther)
		}
	}
	return http.HandlerFunc(fn)
}
