package common

import (
	"dbweb/core"
	"encoding/json"
	"fmt"

	"github.com/linlexing/dbx/schema"
)

//tableDef 完成表定义
type tableDef struct{}
type postResult struct {
	Error string
}
type tableDefField struct {
	Name struct {
		Old string
		New string
	}
	Type    string
	Len     int
	Key     bool
	NotNull bool
	Index   bool
}
type tableDefBody struct {
	Fields []*tableDefField
}

func init() {
	core.RegisterFun("tabledef", new(tableDef), "_layout/blank")
}

//Get 是事件响应
func (t *tableDef) Get(p *core.ElementHandleArgs) {
	q := p.Req.URL.Query()
	dbName := p.User.DecodeQueryValue(q.Get("db"))
	tableName := p.PKS[0]
	p.More["DBName"] = dbName
	db := core.LoadOuterDB(p.DB, dbName)
	tab, err := schema.Find(db.DriverName()).OpenTable(db, tableName)
	if err != nil {
		core.LOG.Panic(err)
	}
	p.More["TableDefine"] = tab
	p.HTML()
}

//Post 是事件响应
func (t *tableDef) Post(p *core.ElementHandleArgs) {
	q := p.Req.URL.Query()
	data := tableDefBody{}
	r := postResult{}
	if err := json.NewDecoder(p.Req.Body).Decode(&data); err != nil {
		r.Error = err.Error()
		p.Render.JSON(200, r)
		return
	}
	dbName := p.User.DecodeQueryValue(q.Get("db"))
	tableName := p.PKS[0]
	db := core.LoadOuterDB(p.DB, dbName)
	tab, err := schema.Find(db.DriverName()).OpenTable(db, tableName)
	if err != nil {
		core.LOG.Panic(err)
	}
	pks := []string{}
	cols := []*schema.Column{}
	for _, one := range data.Fields {
		var col *schema.Column
		if len(one.Name.Old) > 0 {
			col = tab.ColumnByName(one.Name.Old)
			if col == nil {
				r.Error = fmt.Sprintf("在表:%s 中找不到旧名称为:%s 的字段", tableName, one.Name.Old)
				p.Render.JSON(200, r)
				return
			}
			if one.Name.Old != one.Name.New {
				col.FormerName = []string{one.Name.Old}
				col.Name = one.Name.New
			}
			col.TrueType = "" //TrueType需要清空，否则不能修改字段
		} else {
			col = &schema.Column{
				Name: one.Name.New,
			}
			tab.Columns = append(tab.Columns, col)
		}
		col.Type = schema.ParseDataType(one.Type)
		col.MaxLength = one.Len
		col.Index = one.Index
		col.Null = !one.NotNull
		cols = append(cols, col)
		if one.Key {
			pks = append(pks, one.Name.New)
		}
	}

	tab.Columns = cols
	tab.PrimaryKeys = pks
	if err := tab.Update(db.DriverName(), db); err != nil {
		r.Error = err.Error()
	}
	p.Render.JSON(200, r)
}
