// create migration/bulk
package main

import (
	"code.justin.tv/d8a/iceman/lib/bulk"
	"code.justin.tv/d8a/iceman/lib/dbconf"
	"code.justin.tv/d8a/iceman/lib/migrations"
	"errors"
	"github.com/spf13/cobra"
	"os"
	"path/filepath"
	"time"
)

// createCmd represents the create command
var createCmd = &cobra.Command{
	Use:   "create [type] [name]",
	Short: "create a new migration or bulk operation",
	Long:  "This will create a new migration or bulk operation. Make sure you specify which one as well as its name.",
	RunE: func(cmd *cobra.Command, args []string) error {

		if len(args) < 2 {
			return errors.New("Type and name required.")
		}

		_type := args[0]
		_name := args[1]

		utc, err := time.LoadLocation("UTC")
		if err != nil {
			return err
		}

		if _type == "migration" {
			conf, err := dbconf.NewDBConf(path, env, schema, "migrations")
			if err != nil {
				return err
			}
			if err = os.MkdirAll(conf.Dir, 0777); err != nil {
				return err
			}

			n, err := migrations.CreateMigration(_name, conf.Dir, time.Now().In(utc))
			if err != nil {
				return err
			}
			a, e := filepath.Abs(n)
			if e != nil {
				return err
			}

			green.Printf("Successfully created: %v\n", a)
		} else if _type == "bulk" {
			conf, err := dbconf.NewDBConf(path, env, schema, "bulk")
			if err != nil {
				return err
			}
			if err = os.MkdirAll(conf.Dir, 0777); err != nil {
				return err
			}

			n, err := bulk.CreateBulk(_name, conf.Dir, time.Now().In(utc))
			if err != nil {
				return err
			}
			a, e := filepath.Abs(n)
			if e != nil {
				return err
			}

			green.Printf("Successfully created: %v\n", a)
		} else {
			return errors.New("Only 'migration' and 'bulk' supported")
		}

		return nil
	},
}

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