package main

import (
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"time"
)

//PathsConfig all system available pathes
type PathsConfig struct {
	CRMAttachment string `json:"crm_attachment"`
	Angular2App   string `json:"angular2_app"`
}

//TODO: setup GlobalPath Config, from reading file
//GlobalPath all global pathes configurations
var GlobalPath = PathsConfig{
	"/tmp/",
	"/mnt/data/workspace/angular.ts/wechat/ng2-admin/dist/"}

//KFUsers info cache about current customer service
var KFUsers kfCache

func main() {
	err := readConfig() //wechat API config
	if err != nil {
		log.Println(err)
		log.Fatal("unable to read server_config.json, program quit")
		return
	}

	err = readCRMConfig()
	if err != nil {
		log.Println(err)
		log.Fatal("unable to read crm_config.json, program quit")
	}

	initAllProc()
	setupRootFileServer()
	startSessionManager(2048)
	KFUsers.kfRenewList()
	//always the last one
	setupHTTPHandler()

}

func setupHTTPHandler() {
	//setup handler
	//http.HandleFunc("/", webrootHandler)
	http.HandleFunc("/api", apiV1Main)
	http.HandleFunc("/upload", uploadHandler)
	http.HandleFunc("/crmfiles/", crmAttachmentHandler)
	http.HandleFunc("/dumprequest", dumpReuestHandler)
	http.HandleFunc("/MP_verify_6JqVkftKr39GMakA.txt", mpDomainAuthSecret)
	http.HandleFunc("/profile_newly_register", initialRegistrationHandler)
	http.ListenAndServe(":65500", nil)
}

func startSessionManager(concurrent int) {
	m := SessionManager{}
	AllInMessage = make(chan InWechatMsg, concurrent)
	go m.startSessionManager(AllInMessage)
}

func setupRootFileServer() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, GlobalPath.Angular2App+r.URL.Path[1:])
	})

	//fs := http.FileServer(http.Dir("/mnt/data/workspace/angular.ts/ng2-admin/dist"))
	//http.Handle("/test", http.StripPrefix("/test", fs))

	//fs := http.FileServer(http.Dir("/mnt/data/workspace/angular.ts/wechat/ng2-admin/dist"))
	//http.Handle("/", fs)
}

func dumpReuestHandler(w http.ResponseWriter, r *http.Request) {
	logRequestDebug(httputil.DumpRequest(r, true))
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("Access-Control-Allow-Origin", "http://192.168.1.39:4200")
	w.Header().Set("Access-Control-Allow-Headers", "Authorziation11,Authorziation12")
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.Header().Set("Access-Control-Expose-Headers", "Set-Cookie,myheader,*")
	w.Header().Set("myheader", "myheader-data")

	expiration := time.Now().Add(10 * 365 * 24 * time.Hour)
	str := time.Now().String()
	cookie := http.Cookie{Name: "username", Value: str, Expires: expiration}
	http.SetCookie(w, &cookie)

	fmt.Fprintf(w, `{"status":"OK"}`)
	for _, c := range r.Cookies() {
		log.Println(c.Name)
		log.Println(c.Value)
	}
}

// 用户在网页授权页同意授权给公众号后，微信会将授权数据传给一个回调页面，回调页面需在此域名下，以确保安全可靠。
// 注意事项：
// 1、回调页面域名或路径需使用字母、数字及“-”的组合（例：wx.qq.com或wx.qq.com/mp），不支持IP地址、端口号及短链域名。填写的域名或路径需与实际回调URL中的域名或路径相同。
// 2、填写的域名须通过ICP备案的验证。
// 3、将文件MP_verify_6JqVkftKr39GMakA.txt（点击下载）上传至填写域名或路径指向的web服务器（或虚拟主机）的目录（若填写域名，将文件放置在域名根目录下，例如wx.qq.com/MP_verify_6JqVkftKr39GMakA.txt；若填写路径，将文件放置在路径目录下，例如wx.qq.com/mp/MP_verify_6JqVkftKr39GMakA.txt），并确保可以访问。
func mpDomainAuthSecret(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "6JqVkftKr39GMakA")
	//由于需要什么ICP备案，这个功能不能使用
}

//for user's initial registration, especially for wechat users
//they visit a url that is specifically designed for them to
//auth and input their profile data.
//the url's query string will contains a token and a signature
//so that it's verified, by single get request, to allow people to
//enter their details into the CRM system.
//
//this handler, check's the query sting ,set an auth cookie to the client
//and serve angular app, through an URL "/profile/edit"
//or if the user has already been registered,
//redirect user to a URL "/pages/dashboard"
//
func initialRegistrationHandler(w http.ResponseWriter, r *http.Request) {
	//TODO: verify url parameters and make sure its username is correctly set
	//
	expiration := time.Now().Add(10 * 365 * 24 * time.Hour)
	str := time.Now().String()
	cookie := http.Cookie{Name: "username", Value: str, Expires: expiration}
	http.SetCookie(w, &cookie)
	cookie = http.Cookie{Name: "signature", Value: "abcee", Expires: expiration}
	http.SetCookie(w, &cookie)
	http.Redirect(w, r, "http://192.168.1.39:4200/#pages/charts/chartist-js", 307) //302 temp redirect
}
