package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

type kfInfo struct {
	Acc    string `json:"kf_account"`    //
	Nick   string `json:"kf_nick"`       //
	ID     int    `json:"kf_id"`         //
	Avatar string `json:"kf_headimgurl"` //
}

//KFUserList a list of kf users
type kfUserList struct {
	KfList []kfInfo `json:"kf_list"`
}

//KFCache KF user's info cache
type kfCache struct {
	Name2Acc map[string]string //map nickname to account id
	ID2Acc   map[int]string    //map from id to acc
	Users    kfUserList
	UpdateAt int32 //time stamp
	Expire   int32 //time stamp
}

func getKFlistURL() string {
	atk, _ := GetAccessToken()
	return fmt.Sprintf("https://api.weixin.qq.com/cgi-bin/customservice/getkflist?access_token=%s", atk)
}

func (m *kfCache) getKFUsers() (err error) {
	jstr, err := m.kfGetListJSON()
	err = json.Unmarshal([]byte(jstr), &m.Users)
	return
}

func (m *kfCache) kfAcc(nickname string) (acc string) {
	m.kfRenewList()
	return m.Name2Acc[nickname]
}

func (m *kfCache) kfGetListJSON() (jstr string, err error) {
	url := getKFlistURL()
	resp, err := http.Get(url)
	if err != nil {
		return
	}
	b, err := ioutil.ReadAll(resp.Body)
	if err == nil {
		jstr = string(b)
	}
	return
}

func (m *kfCache) kfRenewList() {
	if m.Expire == 0 || m.UpdateAt == 0 || m.Expire < m.UpdateAt {
		log.Println("Renew Kf Info List")
		err := m.getKFUsers()
		if err == nil {
			m.Name2Acc = map[string]string{}
			m.ID2Acc = map[int]string{}
			for _, v := range m.Users.KfList {
				m.Name2Acc[v.Nick] = v.Acc
				m.ID2Acc[v.ID] = v.Acc
			}
			m.UpdateAt = int32(time.Now().Unix())
			m.Expire = m.UpdateAt + 1200 //20 minutes
		}
	}
}

func (m *kfCache) kfGetInfo(nick string) (r kfInfo) {
	m.kfRenewList()
	for _, v := range m.Users.KfList {
		if nick == v.Nick {
			return v
		}
	}
	return
}
