package config

import (
	"fmt"
	"io/ioutil"
	"os"

	"github.com/dgrijalva/jwt-go"

	"github.com/mitchellh/mapstructure"
	"github.com/spf13/viper"
)

var WorkDir = os.Getenv("PASTURE_WORK_DIR")

func Initialize(path string, cfgStruct interface{}) error {
	if WorkDir == "" {
		WorkDir = "."
	}
	dir := fmt.Sprintf("%s/config/%s", WorkDir, path)
	viper.SetConfigType("yaml")
	viper.SetConfigFile(dir)
	if err := viper.ReadInConfig(); err != nil {
		return err
	}
	if err := viper.Unmarshal(&cfgStruct, func(c *mapstructure.DecoderConfig) {
		c.TagName = "yaml"
	}); err != nil {
		return err
	}
	return nil
}

func openPrivateKey() JwtTokenKeyConfig {
	pathList := []string{fmt.Sprintf("%s/config/private.key", WorkDir), fmt.Sprintf("%s/config/public.key", WorkDir)}
	res := JwtTokenKeyConfig{PublicKey: nil, PrivateKey: nil}
	for i, path := range pathList {
		keyConfig, err := os.Open(path)
		if err != nil {
			panic(err)
		}

		b, err := ioutil.ReadAll(keyConfig)
		if err != nil {
			panic(err)
		}

		if i == 0 {
			privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(b)
			if err != nil {
				panic(err)
			}
			res.PrivateKey = privateKey
		}

		if i == 1 {
			publicKey, err := jwt.ParseRSAPublicKeyFromPEM(b)
			if err != nil {
				panic(err)
			}
			res.PublicKey = publicKey
		}
	}

	return res
}