package main

import (
	"encoding/base64"
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
)

//WechatAPIConfig all secret related API Config
type WechatAPIConfig struct {
	//Token is the wechat API shared secrete
	Token string `json:"Token"`

	//EncodingAESKey is the Key for encrypt messages
	EncodingAESKey string `'json:"EncodingAESKey"`

	//Appid is wechat public account appid
	Appid string `json:"Appid"`

	//AppSecret is how we identify ourselves.
	AppSecret string `json:"AppSecret"`

	//AuthTokenSaveTo
	AuthTokenSaveTo string `json:"AuthTokenSaveTo"`

	//PublicAccountID
	PublicAccountID string `json:"PublicAccountID"`
}

//APIConfig contains secrets that cannot store in source file
var APIConfig WechatAPIConfig

func readConfig() error {

	log.Printf("read Wechat API config from %s\r\n", "server_config.json")
	body, err := ioutil.ReadFile("server_config.json")
	if err != nil {
		log.Fatal("Cannot read config from server_config.json")
		return err
	}
	err = json.Unmarshal(body, &APIConfig)
	if APIConfig.AppSecret == "" {
		return errors.New("AppSecret not available")
	}
	if APIConfig.Appid == "" {
		return errors.New("AppId not available")
	}
	if APIConfig.AuthTokenSaveTo == "" {
		return errors.New("where to save accesstoken is unknown")
	}
	if APIConfig.EncodingAESKey == "" {
		return errors.New("unknown AesEncryptionKey")
	}
	if APIConfig.Token == "" {
		return errors.New("hidden shared secret token is empty")
	}
	return err
}

//convert AesEncryptKey into Binary 32bytes
func getAesEncryptKey() [32]byte {
	key, _ := base64.StdEncoding.DecodeString(APIConfig.EncodingAESKey + "=")
	var k [32]byte
	copy(k[:], key)
	return k
}
