package api

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/gorilla/mux"
	"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 (
	selectUniqueTeacherClasses = `
SELECT DISTINCT classes.* FROM activities 
INNER JOIN classes on classes.id=activities.class_id 
WHERE teacher_id=?`

	selectUniqueTeacherSubjects = `
SELECT DISTINCT subjects.* FROM activities 
INNER JOIN subjects on subjects.id=activities.subject_id 
WHERE activities.teacher_id=?`
)

func teachersHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		teachers, err := orm.GetTeachersAll()
		if err != nil {
			renderer.Render[r.URL.Query()["format"][0]](w, r, err)
		} else {
			renderer.Render[r.URL.Query()["format"][0]](w, r, teachers, r.URL.Query())
		}
	}
	return http.HandlerFunc(fn)
}

func teacherShowHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		teacher, err := orm.GetTeacherAll(mux.Vars(r)["id"])
		if err != nil {
			renderer.Render[r.URL.Query()["format"][0]](w, r, err)
		} else {
			renderer.Render[r.URL.Query()["format"][0]](w, r, teacher, r.URL.Query())
		}
	}
	return http.HandlerFunc(fn)
}

func teachersAddHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			teacher, err := orm.GetTeacher(mux.Vars(r)["id"])
			if err != nil {
				renderer.Render[r.URL.Query()["format"][0]](w, r, err)
			} else {
				renderer.Render[r.URL.Query()["format"][0]](w, r, teacher, r.URL.Query())
			}
		} else if r.Method == "POST" {
			teacher := new(orm.Teacher)
			err := renderer.Decode(teacher, r)
			if err != nil {
				panic(err)
			}
			_, err = orm.SaveTeacher(teacher)
			if err != nil {
				panic(err)
			}
			http.Redirect(w, r, fmt.Sprintf("/teachers/%d?format=html&tpl_layout=base&tpl_content=teachers_show", teacher.ID), http.StatusSeeOther)
		}

	}
	return http.HandlerFunc(fn)
}

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

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

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

		data.RedirectUrl = "/teachers"

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

func teacherUpdateHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "GET" {
			teacher, err := orm.GetTeacher(mux.Vars(r)["id"])
			if err != nil {
				renderer.Render[r.URL.Query()["format"][0]](w, r, err)
			} else {
				renderer.Render[r.URL.Query()["format"][0]](w, r, teacher, r.URL.Query())
			}
		} else if r.Method == "POST" {
			teacher, err := orm.GetTeacher(mux.Vars(r)["id"])
			if err != nil {
				panic(err)
			}
			err = renderer.Decode(teacher, r)
			if err != nil {
				panic(err)
			}
			_, err = orm.SaveTeacher(teacher)
			if err != nil {
				panic(err)
			}
			http.Redirect(w, r, fmt.Sprintf("/teachers/%d?format=html&tpl_layout=base&tpl_content=teachers_show", teacher.ID), http.StatusSeeOther)
		}

	}
	return http.HandlerFunc(fn)
}

func teachersCheckUsernameHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		var teacher orm.Teacher
		var data struct {
			Exists bool `json:"exists"`
		}

		if orm.DB().Where("username = ?", mux.Vars(r)["username"]).Find(&teacher).RecordNotFound() {
			data.Exists = false
		} else {
			data.Exists = true
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(data)

	}
	return http.HandlerFunc(fn)
}

func teachersImportHandler() http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		r.ParseMultipartForm(32 << 20)
		file, _, err := r.FormFile("teachers_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{
				"COGNOME": "surname",
				"NOME":    "name",
			},
		); err != nil {
			panic(err)
		} else {
			if err := orm.Import(&orm.Teacher{}, importer); err != nil {
				panic(err)
			}
			http.Redirect(w, r, "/teachers", http.StatusSeeOther)
		}
	}
	return http.HandlerFunc(fn)
}
