package models_func

import (
	"errors"

	"github.com/dabory/abango-rest"
	e "github.com/dabory/abango-rest/etc"
)

// 이것 안쓰는 펑션이지만 다른것에 사용 가능하므로 일단 내비둠.
// func LastSeqNoGet(y *abango.Controller, table string, idName string, hdId int) (int, error) {

// 	seqNo := 0
// 	sql := " select MAX(seq_no) as last_seq_no from " + locals.Tpf + table
// 	sql += " where " + idName + " = " + e.NumToStr(hdId)
// 	sql += " group by " + idName

// 	if rs, err := y.Db.Query(sql); err == nil { //레코드가 없으면 넣어놓은 seqNo 는 0으로 유지 된다.
// 		for _, val := range rs {
// 			for _, val := range val {
// 				seqNo, _ = strconv.Atoi(string(val))
// 				// fmt.Println(val, string(val))
// 			}
// 		}
// 		e.FuncRun("wqerfvdfgherh", e.CurrFuncName())
// 		return seqNo + 1, nil //마지막번호에서 1을 더한다.
// 	} else {
// 		return 0, errors.New(e.FuncRunErr("owqrkmpofae", e.CurrFuncName()+err.Error()))
// 	}
// }

type SeqNoUpDownReq struct {
	BdTableName string
	HdIdName    string
	HdId        int
	CurrId      int
	Move        string
	QueryCnt    int64
}

type SeqNoUpDownFuncSet struct {
	SeqNoUpDownReq
	CurrSeqNo int
	Page      []SeqNoUpDownSingle
}

type SeqNoUpDownSingle struct {
	Id    int
	SeqNo int
}

func (t *SeqNoUpDownFuncSet) SeqNoUpDown(y *abango.Controller) error {

	//NextVersion Deprecates
	// tblName := t.BdTableName
	// if strings.Contains(t.BdTableName, "main_") || strings.Contains(t.BdTableName, "pro_") {
	// 	tblName = t.BdTableName
	// } else {
	// 	tblName = "dbr_" + t.BdTableName
	// }

	qry := *y.Db.
		Table(t.BdTableName).
		Select("id, seq_no").
		Where(t.HdIdName + "=" + e.NumToStr(t.HdId)).
		Asc("seq_no")

	if err := qry.Find(&t.Page); err == nil {
		// if cnt, err := qry.FindAndCount(&t.Page); err == nil {
		// t.QueryCnt = cnt
		e.FuncRun("wpkjcapqjd", e.CurrFuncName())
		// return nil //마지막번호에서 1을 더한다.
	} else {
		return errors.New(e.PageQryErr("dfgdresgfsf", e.CurrFuncName()+err.Error()))
	}

	currKey := 0
	currSeqNo := 0
	for key, r := range t.Page {
		if r.Id == t.CurrId {
			currKey = key
			currSeqNo = r.SeqNo
			break
		}
	}

	if currSeqNo == 0 {
		return errors.New(e.PageQryErr("otjnsaefvq", " SeqNo does NOT exist. Check HdId/CurrID !"))
	}

	targetId := 0
	targetSeqNo := 0
	if t.Move == "up" {
		if currKey == 0 {
			return errors.New(e.PageQryErr("otjnsaefvq", "Current SeqNo is the first one "))
		} else {
			targetId = t.Page[currKey-1].Id
			targetSeqNo = t.Page[currKey-1].SeqNo
		}
	} else if t.Move == "down" {
		if currKey == len(t.Page)-1 {
			return errors.New(e.PageQryErr("iueytbwerfas", "Current SeqNo is the last one "))
		} else {
			targetId = t.Page[currKey+1].Id
			targetSeqNo = t.Page[currKey+1].SeqNo
		}
	} else {
		return errors.New(e.PageQryErr("klkfefasfwcv", "Value of Move should be \"up\" or \"down\" "))
	}

	sess := y.Db.NewSession()
	if err := sess.Begin(); err == nil {
		defer sess.Close()
	} else {
		return errors.New(e.PageQryErr("otyhjnsefㄹㅇ", "Transaction Action Failed "))
	}

	strSql := "update " + t.BdTableName + " set seq_no = ? where id = ? "
	if _, err := y.Db.Exec(strSql, currSeqNo, targetId); err != nil {
		return errors.New(e.FuncRunErr("nbhserfvaew", e.CurrFuncName()+err.Error()))
	}

	if _, err := y.Db.Exec(strSql, targetSeqNo, t.CurrId); err != nil {
		return errors.New(e.FuncRunErr("oyujxerfsew", e.CurrFuncName()+err.Error()))
	}

	if err := sess.Commit(); err == nil {
		t.CurrSeqNo = currSeqNo
		e.FuncRun("ptervafhhf", e.CurrFuncName())
		return nil
	} else {
		return errors.New(e.FuncRunErr("oyujxerfsew", "Transaction Commit Failed"))
	}

}
