// migration status
package main

import (
	"code.justin.tv/d8a/iceman/lib/dbconf"
	"code.justin.tv/d8a/iceman/lib/status"
	"fmt"
	"github.com/spf13/cobra"
)

var statusCmd = &cobra.Command{
	Use:   "status",
	Short: "display current status of db",
	Long:  "This will show you which migrations have already been applied and which ones are still pending.",
	RunE: func(cmd *cobra.Command, args []string) error {

		conf, err := dbconf.NewDBConf(path, env, schema, "migrations")
		if err != nil {
			return err
		}

		statuses, err := status.OrganizeStatuses(conf)
		if err != nil {
			return err
		}
		max := status.GetMaxLength(statuses)

		fmt.Printf("\nStatus for environment: %v\n\n", conf.Env)
		fmt.Printf(padAround("Migration", " ", max-4) + "||          Created At          ||          Applied At          \n")
		fmt.Printf(padAround("", "=", max+32) + "\n")

		for _, s := range statuses {
			if s.State == status.CompletedState {
				green.Printf("%v%29v%32v\n", padAround(s.Name, " ", max-len(s.Name)/2), s.Created.Format("2006-01-02 15:04:05.000"), s.Applied.Format("2006-01-02 15:04:05.000"))
			} else if s.State == status.PendingState {
				yellow.Printf("%v%29v%25v\n", padAround(s.Name, " ", max-len(s.Name)/2), s.Created.Format("2006-01-02 15:04:05.000"), "<PENDING>")
			} else { // red
				red.Printf("%v%29v%32v\n", padAround(s.Name, " ", max-len(s.Name)/2), s.Created.Format("2006-01-02 15:04:05.000"), s.Applied.Format("2006-01-02 15:04:05.000"))
			}
		}
		fmt.Println("")
		return nil
	},
}

func init() {
	RootCmd.AddCommand(statusCmd)
}

// pad strings with characters to fill a certain length
func padAround(str string, pad string, length int) string {
	if len(str)%2 == 0 {
		for i := 0; i < length+1; i++ {
			str = pad + str
		}
	} else {
		for i := 0; i < length; i++ {
			str = pad + str
		}
	}

	for i := 0; i < length; i++ {
		str += pad
	}
	return str
}
