package comm

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/golang-migrate/migrate/v4"
	"github.com/golang-migrate/migrate/v4/database/mongodb"
	_ "github.com/golang-migrate/migrate/v4/source/file"
)

func AppMongoMiration() {

	///data/migrations==mongodb://root:3dshow@3dshow-mongo-alpha:27017/dbname?query&&/data/migrations==mongodb://user:password@host:port/dbname?query
	config := "mongo-migrations==mongodb://root:copter-train-8888@127.0.0.1:27017/user?authSource=admin"
	// config := os.Getenv("MONGO_MIGRATIONS")
	// if len(config) < 1 {
	// 	return
	// }
	path, err := os.Executable()
	if err != nil {
		panic("mongo-migration get exe path err=>" + err.Error())
	}
	exePath := filepath.Dir(path)
	exePath = strings.Replace(exePath, "\\", "/", -1)

	dbs := strings.Split(config, "&&")
	fmt.Println("mongo_migrations_dbs: ", dbs)

	for _, db := range dbs {

		frags := strings.Split(db, "==")
		if len(frags) != 2 {
			panic("mongo-migration config err=>" + db)
		}

		sourc := frags[0]
		dbUri := frags[1]
		p := &mongodb.Mongo{}
		d, err := p.Open(dbUri)
		if err != nil {
			panic("mongo-migration open err=>" + err.Error())
		}
		_sourc := fmt.Sprintf("%s/%s", exePath, sourc)
		fileSource := fmt.Sprintf("file://%s", _sourc)
		fmt.Println("mongo_migrations_file_source: ", fileSource)
		mi, err := migrate.NewWithDatabaseInstance(fileSource, "", d)
		if err != nil {
			panic("mongo-migration new instance err=>" + err.Error())
		}
		err = mi.Up()
		if err != nil {
			fmt.Println("mongo-migration up err=>" + err.Error())
		}

	}
}
