package main

import (
	"fmt"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

func spaEditMeetingHandler(w http.ResponseWriter, r *http.Request) {
	lead, found := getLeadFromRequest(r)
	if !found {
		response403Handler(w)
		// w.WriteHeader(http.StatusUnauthorized)
		// fmt.Fprintf(w, "User not found ")
		return
	}

	meeting, found := getMeetingFromRequest(r)

	switch r.Method {
	case "GET":
		if !found {
			//empty meeting
			meeting.showEdit(w)
			return
		}
		if lead.ID != meeting.ParentID { //is the meeting belongs to this user?
			response403Handler(w)
			return
		}
		//editing existing meeting
		meeting.showEdit(w)
	case "POST":
		if found && (lead.ID != meeting.ParentID) { //is the meeting belongs to this user?
			response403Handler(w)
			return
		}
		meeting.saveFromWeb(w, r)
	default:
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(w, "Unsupported Method %s", r.Method)
	}

	// e, err := crmGetEntity("Meeting", "595d064a6e372fc1f")
	// log.Println(err)
	// meeting, ok := e.(crmdMeeting)
	// log.Println(ok)
	// spaEditMeetingPopulateMeetingInfo(w, meeting)
}

func (m crmdMeeting) showEdit(w http.ResponseWriter) {
	tTest := template.New("spaEditMeeting")
	str, err := ioutil.ReadFile("spa/editmeeting.html")
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Formating information not available.")
		return
	}
	tTest, err = tTest.Parse(string(str))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Formating instruction invalid")
		return
	}
	err = tTest.Execute(w, m)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Monkey runs into our computer room...")
		log.Println("ERROR: Template execution on spa/Edit, failed \n" + err.Error())
	}
}

func getMeetingFromRequest(r *http.Request) (meeting crmdMeeting, found bool) {
	q, err := url.ParseQuery(r.URL.RawQuery)
	if err != nil {
		return
	}

	id, ok := q["mid"] //meetingid
	if !ok {
		return
	}
	meeting, err = crmGetMeeting(id[0])

	if err != nil {
		found = false
		log.Printf("WARNING: cannot find meeting with id [%s]", id[0])
		return
	}
	found = true
	return
}

func (m crmdMeeting) saveFromWeb(w http.ResponseWriter, r *http.Request) {

	meeting := crmdMeeting{}
	err := r.ParseMultipartForm(32 << 20)
	if err != nil {
		response400Handler(w)
		return
	}

	//if !checkCSRF(r.Form["csrf"])
	//csrf, ook := r.Form["csrf"]
	ok := meeting.validateFormInput(r.Form)
	if !ok {
		meeting.showEdit(w)
		return
	}

	//check to see if there is file, cover picture
	meeting.validateFormFile(r)

	meeting.ID = m.ID
	updatedMeeting, err := meeting.save()
	if err == nil {
		updatedMeeting.showEdit(w)
		return
	}

	response500Handler(w)
}

func (m *crmdMeeting) validateFormInput(form url.Values) bool {

	val, ok := form["meetingname"]
	if ok {
		m.Name = val[0]
	} else {
		m.addSpaErr("活动主题/标题不能为空")
	}

	val, ok = form["description"]
	if ok {
		m.Description = val[0]
	} else {
		m.addSpaErr("清添加描述活动本身")
	}

	startdate, sok := form["startdate"]
	starthour, hok := form["starthour"]
	duration, rok := form["duration"]
	if sok && hok && rok {
		m.buildStartDate(startdate[0], starthour[0], duration[0])
	} else {
		m.addSpaErr("活动日期，开始时间，持续时间 不能为空")
	}

	val, ok = form["venue"]
	if ok {
		m.Venue = val[0]
	} else {
		m.addSpaErr("请添加活动地点/集合地点")
	}

	return !m.hasError()
}

func (m *crmdMeeting) validateFormFile(r *http.Request) (ok bool) {
	file, _, err := r.FormFile("cover")
	if err == nil {
		defer file.Close()
		f, err := ioutil.TempFile(os.TempDir(), "wechat_hitxy_spa_edit_meeting")
		if err == nil {
			defer f.Close()
			io.Copy(f, file)
			attch, err := crmCreateAttachment(f.Name())
			if err == nil {
				m.CoverID = attch.ID
				os.Remove(f.Name())
				return true
			}
		}
	}
	return false
}

func (m *crmdMeeting) buildStartDate(date, hour, duration string) {
	layout := "2 January, 2006 15:04 MST"
	value := strings.TrimSpace(date) + " " + strings.TrimSpace(hour) + " AEST" //Force Sydney time
	t, err := time.Parse(layout, value)
	if err != nil {
		m.addSpaErr("开始日期，时间，无法识别")
		return
	}
	utc, err := time.LoadLocation("UTC")
	if err == nil {
		m.DateStart = t.In(utc).Format(getCrmTimeLayout())
		log.Println(m.DateStart)

		m.buildDuration(duration)
		m.DateEnd = t.In(utc).Add(time.Second * time.Duration(m.Duration)).Format(getCrmTimeLayout())
	}
}

func (m *crmdMeeting) buildDuration(duration string) {
	var hour, minute int
	cnt, err := fmt.Sscanf(duration, "%d:%d", &hour, &minute)
	if cnt != 2 && err != nil {
		m.addSpaErr("持续时间不正确")
		return
	}
	m.Duration = (hour * 3600) + (minute * 60)
}
