package main

import (
	"encoding/json"
	"errors"
	"log"
)

type crmdLocation struct {
	crmdEntityBase
	Latitude   float64 `json:"latitude"`
	Longtitude float64 `json:"longtitude"`
	Precision  float64 `json:"precision"`
	LeadID     string  `json:"leadId,omitempty"`
}

//record location
func onLocation(in* InWechatMsg) {
	openID := in.header.FromUserName

	lead, found, err := crmFindLeadByOpenID(openID)
	if found && err == nil {
		e := in.body.(EventMsg)
		//save info
		info := crmdLocation{}
		info.Name = in.header.FromUserName
		info.LeadID = lead.ID
		info.Longtitude = e.Longitude
		info.Latitude = e.Latitude
		info.Precision = e.Precision
		info.Save()
	}
}

func (m crmdLocation) Save() (location crmdLocation, err error) {
	jsonB, err := json.Marshal(m)
	if err != nil {
		log.Println(err)
		return
	}

	entity, err := crmCreateEntity("Location", jsonB)
	if err != nil {
		log.Println(err)
		return
	}

	location, ok := entity.(crmdLocation)
	if !ok {
		err = errors.New("incorrect entity cannot convert to Location")
	}
	log.Println(location)
	return
}
