package main

import (
	"fmt"
	"net/http"
	"net/url"
)

func crmcache(w http.ResponseWriter, r *http.Request) {
	//debugDumpHTTPRequest(r)
	if !checkSignatureByToken(r, IntraAPIConfig.CRMSecrete) {
		w.WriteHeader(http.StatusUnauthorized)
		fmt.Fprintf(w, "Expired or invalid link")
		return
	}

	v, err := url.ParseQuery(r.URL.RawQuery)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "parse query not valid")
		return
	}
	attachmentid, ok := v["a"]
	if !ok {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "reference number is not found")
		return
	}
	id := attachmentid[0]
	path := crmcacheFileName(id)

	if isFileExist(path) {
		http.ServeFile(w, r, path)
		return
	}
	err = crmDownloadAttachmentAs(id, path)

	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		fmt.Fprintf(w, "reference number is not right")
		return
	}
	if isFileExist(path) {
		http.ServeFile(w, r, path)
		return
	}
	w.WriteHeader(http.StatusInternalServerError)
	fmt.Fprintf(w, "cannot build reference cache")
}

func crmcacheFileName(id string) string {
	return CRMConfig.AttachmentCache + id
}
