package main

import (
	"encoding/json"
	"fmt"

	"strings"

	_ "github.com/go-sql-driver/mysql"
	"xorm.io/xorm"
)

var xEngine *xorm.Engine

func XormConnectDatabaseWithUri(sql string) (*xorm.Engine, error) {
	//	sqlStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=true&loc=Local", db.User, db.Password, db.Host, db.Port, db.Name)
	sqlStr := fmt.Sprintf("%s?charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=true&loc=Local", sql)
	//	fmt.Printf("sqlStr:%s:******@tcp(%s:%s)/%s?charset=utf8mb4&collation=utf8mb4_general_ci&parseTime=true&loc=Local", db.User, db.Host, db.Port, db.Name)
	var err error
	xEngine, err = xorm.NewEngine("mysql", sqlStr) //1、Create xorm engine
	if err != nil {
		fmt.Println("Failed to connect database:", err)
		return nil, err
	}
	xEngine.ShowSQL(true)
	return xEngine, nil
}

type MmlCommand struct {
	//	Id         int    `json:"id" xorm:"pk 'id' autoincr"`
	NeType     string `json:"neType"`
	Category   string `json:"category"`
	CatDisplay string `json:"catDisplay" xorm:"cat_display"`
	Operation  string `json:"operation"`
	Object     string `json:"object"`
	MmlDisplay string `json:"mmlDisplay" xorm:"mml_display"`
	ParamJson  string `json:"paramJson"`
	Status     string `json:"status"`
}

func XormInsertMMLConfig(mapJson *map[string]interface{}, tableName string) (int64, error) {
	var affected, a int64
	var err error
	mmlCommand := new(MmlCommand)

	for n, d := range *mapJson {
		if d == nil {
			break
		}
		fmt.Println("n:", n)
		mmlCommand.NeType = strings.ToUpper(n)
		//		for c, ma := range d.(map[string]interface{}) {
		for c, ci := range d.(map[string]interface{}) {
			fmt.Println("c:", c)
			fmt.Println("ci:", ci)
			mmlCommand.Category = c
			mmlCommand.CatDisplay = fmt.Sprintf("%v", ci.(map[string]interface{})["display"])
			mml := ci.(map[string]interface{})["mml"]
			for m, mi := range mml.([]interface{}) {
				fmt.Println("m:", m)
				fmt.Println("mi:", mi)
				mmlCommand.Operation = fmt.Sprintf("%v", mi.(map[string]interface{})["operation"])
				mmlCommand.Object = fmt.Sprintf("%v", mi.(map[string]interface{})["object"])
				mmlCommand.MmlDisplay = fmt.Sprintf("%v", mi.(map[string]interface{})["display"])
				if mi.(map[string]interface{})["status"] == nil {
					mmlCommand.Status = "Active"
				} else {
					mmlCommand.Status = fmt.Sprintf("%v", mi.(map[string]interface{})["status"])
				}
				pj, _ := json.Marshal(mi.(map[string]interface{})["params"])
				mmlCommand.ParamJson = string(pj)

				fmt.Println("mmlCommand:", mmlCommand)

				session := xEngine.NewSession()
				defer session.Close()
				_, err = session.
					Table(tableName).
					Where("ne_type = ? and category = ? and operation = ? and object = ?", mmlCommand.NeType, mmlCommand.Category, mmlCommand.Operation, mmlCommand.Object).
					Delete()
				if err != nil {
					fmt.Printf("Failed to delete %s: %v\n", tableName, err)
				}
				a, err = session.Table(tableName).Insert(mmlCommand)
				if err != nil {
					fmt.Printf("Failed to insert %s: %v\n", tableName, err)
				}
				affected += a
			}
		}

	}

	return affected, err
}
