package cmd

import (
    "bufio"
    "fmt"
    "github.com/spf13/cobra"
    "github.com/spf13/viper"
    "golang.org/x/term"
    "os"
    pastee "paste.ee/go"
)

var loginCmd = &cobra.Command{
    Use:   "login",
    Short: "Login with an account and store a user access token",
    Long: `Logs into the Paste.ee API and stores a user access token to associate pastes to your account.`,
    Run: loginCommandHandler,
}

func init() {
    loginCmd.Flags().StringP("username", "u", "", "Username")
    loginCmd.Flags().StringP("password", "p", "", "Password")
}

// loginCommandHandler handles the login command from cobra
func loginCommandHandler(cmd *cobra.Command, args []string) {
    client := pastee.New(viper.GetString("apiKey"))

    username, err := cmd.Flags().GetString("username")

    reader := bufio.NewReader(os.Stdin)

    if username == "" || err != nil {
        for {
            fmt.Print("Username: ")
            username, err = reader.ReadString('\n')

            if err != nil {
                return
            } else if username == "" {
                continue
            }

            break
        }
    }

    password, err := cmd.Flags().GetString("password")

    if password == "" || err != nil {
        for {
            fmt.Print("Password: ")
            passwordBytes, err := term.ReadPassword(int(os.Stdin.Fd()))

            if err != nil {
                password, err = reader.ReadString('\n')

                if password != "" {
                    break
                } else {
                    continue
                }
            }

            password = string(passwordBytes)

            break
        }
    }

    res, err := client.Authenticate(username, password)

    if err != nil {
        cmd.PrintErrln("Unable to authenticate:", err)
        os.Exit(1)
    }

    if !res.Success {
        cmd.PrintErrln("Invalid username or password")
        os.Exit(1)
    }

    viper.Set("apiKey", res.Key)
    err = viper.WriteConfig()

    if err != nil {
        cmd.PrintErrln("Unable to write config:", err)
    }

    cmd.Println("Success!")
}