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/renderer"
	"gogs.carducci-dante.gov.it/karmen/datasource/edt"
	"gogs.carducci-dante.gov.it/karmen/orm"
)

func classesHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var data struct {
			Classes []orm.Class
		}
		if err := orm.DB().Preload("Teachers").Find(&data.Classes).Error; err != nil {
			panic(err)
		}
		sort.Slice(data.Classes, func(i, j int) bool {
			return strings.ToLower(data.Classes[i].Name) < strings.ToLower(data.Classes[j].Name)
		})
		if err := renderer.Render(w, "base", "classes", data); err != nil {
			panic(err)
		}
	}
	return http.HandlerFunc(fn)
}

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

		if err := orm.DB().Model(&data.Class).Preload("Subjects").Related(&data.Teachers, "Teachers").Error; err != nil {
			panic(err)
		}

		sort.Slice(data.Teachers, func(i, j int) bool {
			return strings.ToLower(data.Teachers[i].Surname) < strings.ToLower(data.Teachers[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)
			}

			if class.CoordinatorID != 0 {
				var coordinator orm.Teacher
				if err := orm.DB().First(&coordinator, class.CoordinatorID).Error; err != nil {
					panic(err)
				}
				if err := orm.DB().Model(&class).Association("Teachers").Append(coordinator).Error; err != nil {
					panic(err)
				}
			}

			if class.MinuterID != 0 {
				var minuter orm.Teacher
				if err := orm.DB().First(&minuter, class.MinuterID).Error; err != nil {
					panic(err)
				}
				if err := orm.DB().Model(&class).Association("Teachers").Append(minuter).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)
			}

			if class.CoordinatorID != 0 {
				var coordinator orm.Teacher
				if err := orm.DB().First(&coordinator, class.CoordinatorID).Error; err != nil {
					panic(err)
				}
				if err := orm.DB().Model(&class).Association("Teachers").Append(coordinator).Error; err != nil {
					panic(err)
				}
			}

			if class.MinuterID != 0 {
				var minuter orm.Teacher
				if err := orm.DB().First(&minuter, class.MinuterID).Error; err != nil {
					panic(err)
				}
				if err := orm.DB().Model(&class).Association("Teachers").Append(minuter).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)
}
