package cmd

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

	"code.justin.tv/cplat/twitchling/project"
	"github.com/pelletier/go-toml"
	"github.com/spf13/cobra"
)

var initCmd = &cobra.Command{
	Use:   "init",
	Short: "initialize a new Twitchling project",
	Long: `Init (twitchling init) will initialize the current working directory
as a Twitchling project.

The generated project file is stored as project.toml.

Example: twitchling init`,
	RunE: runInit,
}

func init() {
	rootCmd.AddCommand(initCmd)
}

func runInit(cmd *cobra.Command, args []string) error {
	reader := bufio.NewReader(os.Stdin)

	fmt.Print("Smartling user ID: ")
	smartlingUserID, err := readInput(reader)
	if err != nil {
		return err
	}

	fmt.Print("Smarlting project ID: ")
	smartlingProjectID, err := readInput(reader)
	if err != nil {
		return err
	}

	fmt.Print("Sandstorm Role ARN: ")
	sandstormRoleARN, err := readInput(reader)
	if err != nil {
		return err
	}

	fmt.Print("Sandstorm Secret Name: ")
	sandstormSecretName, err := readInput(reader)
	if err != nil {
		return err
	}

	project := project.Project{
		Config: project.ProjectConfig{
			Smartling: project.SmartlingSettings{
				ProjectID: smartlingProjectID,
				UserID:    smartlingUserID,
			},
			Sandstorm: project.SandstormSettings{
				SecretName: sandstormSecretName,
				RoleARN:    sandstormRoleARN,
			},
		},
		MessageSet: project.MessageSet{
			Messages: []project.Message{
				{
					ID: "example",
					Variants: map[string]string{
						"default": "This is an example string",
					},
				},
			},
		},
	}

	data, err := toml.Marshal(project)
	if err != nil {
		return err
	}

	err = ioutil.WriteFile(projectFile, data, 0644)
	if err != nil {
		return err
	}

	fmt.Printf("DONE: Successfully created new Twitchling project %s\n", projectFile)

	return nil
}

func readInput(reader *bufio.Reader) (string, error) {
	input, err := reader.ReadString('\n')
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(input), nil
}
