package config

import (
  "fmt"
  "os"
  "errors"
  "encoding/json"
  "io/ioutil"
  "github.com/mitchellh/go-homedir"
)

type ConfigurationConfig struct {
  Key string `json:"key"`
  Path string `json:"path"`
}

type configuration struct {
  AccessToken string `json:"accessToken"`
  Configs []ConfigurationConfig `json:"configs"`
}

func getConfigFilePath() string {
  configFile, _ := homedir.Expand("~/.dotty.json")
  return configFile
}

func Exists() bool {
  if _, err := os.Stat(getConfigFilePath()); err == nil {
    return true
  }
  return false
}

func Load() *configuration {
  if Exists() {
    file, _ := os.Open(getConfigFilePath())
    decoder := json.NewDecoder(file)
    configuration := configuration{}
    err := decoder.Decode(&configuration)
    if err != nil {
      fmt.Fprintf(os.Stderr, "Unable to read config file. May be corrupted.\n")
      os.Exit(1)
    }
    return &configuration
  }
  return &configuration{Configs: make([]ConfigurationConfig, 0)}
}

func Store(conf *configuration) {
  configJson, _ := json.MarshalIndent(*conf, "", "  ")
  err := ioutil.WriteFile(getConfigFilePath(), configJson, 0600)
  if err != nil{
    panic(err)
  }
}

func DotfileInfo(conf *configuration, key *string) (*ConfigurationConfig, error){
  for _, configFile := range conf.Configs {
    if configFile.Key == *key{
      return &configFile, nil
    }
  }
  return nil, errors.New("Unable to find config.")
}
