package main

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

func spaEditProfile(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "GET":
		lead, found := getLeadFromRequest(r)
		if !found {
			response404Handler(w)
			// w.WriteHeader(http.StatusUnauthorized)
			// fmt.Fprintf(w, "User not found ")
			return
		}
		spaEditProfilePopulateLeadInfo(w, lead)
	case "POST":
		spaEditProfileSaveLead(w, r)
	default:
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(w, "Unsupported Method %s", r.Method)
	}
	//http.ServeFile(w, r, "spa/edit.html")
	//lead, _ := crmGetLead("595a323d4d639d84d")
	//spaEditProfilePopulateLeadInfo(w, lead)
}

func getLeadFromRequest(r *http.Request) (lead crmdLead, found bool) {
	id, found := getLeadIDFromCookie(r)
	if !found {
		return
	}
	lead, err := crmGetLead(id)
	if err != nil {
		found = false
		log.Printf("WARNING: valid cookie lead id %s, not found in EntityCRM", id)
		return
	}
	found = true
	return
}

func spaEditProfilePopulateLeadInfo(w http.ResponseWriter, lead crmdLead) {
	tTest := template.New("spaEditProfile")
	str, err := ioutil.ReadFile("spa/edit.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, lead)
	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 spaEditProfileSaveLead(w http.ResponseWriter, r *http.Request) {
	original, found := getLeadFromRequest(r)
	if !found {
		response403Handler(w)
		log.Println("ERROR: trying to spa/edit lead, but not found")
		return
	}

	err := r.ParseMultipartForm(32 << 20)
	if err == nil {
		for k, v := range r.Form {
			fmt.Println("key:", k)
			fmt.Println("val:", strings.Join(v, ""))
		}
		lastname, lok := r.Form["lastname"]
		email, eok := r.Form["email"]
		phone, pok := r.Form["phone"]
		description, dok := r.Form["description"]

		lead := crmdLead{} //create a patch info,  we cannot reuse original, as it as emailAdressData, phoneNumberData array. it will prevent us from updating email address and phone number, unless we modify them as well.
		lead.ID = original.ID
		if lok && eok && pok && dok {
			lead.LastName = lastname[0]
			lead.EmailAddress = email[0]
			lead.PhoneNumber = phone[0]
			lead.Description = description[0]
			if original.FirstName == "Anonymous" {
				lead.FirstName = "\u0020" //a visible space
			}
			log.Println(original.Status)
			if original.Status == "New" || original.Status == "Anonymous" {
				log.Println("change status to Assigned")
				lead.Status = "Assigned"
			}

			//check to see if there is file
			file, handler, err := r.FormFile("avatar")
			if err == nil {
				defer file.Close()
				log.Printf("%v", handler.Header)
				log.Println(handler.Filename)
				f, err := ioutil.TempFile(os.TempDir(), "wechat_hitxy_spa_edit_lead")
				//os.OpenFile("/tmp/wechat_hitxy_avatar_upload.jpg", os.O_WRONLY|os.O_CREATE, 0666)
				if err == nil {
					defer f.Close()
					io.Copy(f, file)
					attch, err := crmCreateAttachment(f.Name())
					if err == nil {
						lead.AvatarID = attch.ID
						os.Remove(f.Name())
					}
				}
			}
		}
		updatedLead, err := lead.Save()
		log.Println(updatedLead.PhoneNumber)
		log.Println(updatedLead.EmailAddress)
		log.Println(updatedLead.ID)
		if err == nil {
			spaEditProfilePopulateLeadInfo(w, updatedLead)
			//fmt.Fprintf(w, `{"status": "succes"}`)
			return
		}
	}

	fmt.Fprintf(w, `{"status": "error"}`)

}
