package models_table

import (
	"errors"
	"syncscan-go/locals"

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

func (t *EthBlock) TableName() string { // 반드시 있어야 table name을 가져올 수 있다.
	return e.TableName(*t)
}

func (t *EthBlock) RecordName() string { //필수
	return "Id of " + e.NumToStr(t.Id) + " in " + e.TableName(*t) + " "
}

func (t *EthBlock) GetaRow(y *locals.SyncController) error {
	if has, err := y.Db.Get(t); has == true {
		e.RecRead("dfefefqef", t.RecordName())
		return nil
	} else {
		if err == nil {
			return errors.New(e.RecNotFound("wecasdfw", t.RecordName()))
		} else {
			return errors.New(e.RecReadErr("dsflkjfyfd", t.RecordName()+err.Error()))
		}
	}
}

func (t *EthBlock) AddaRow(y *locals.SyncController) error {
	if affected, err := y.Db.Insert(t); affected == 1 && err == nil {
		e.RecAdded("eradsfvzc", t.RecordName())
		return nil
	} else {
		if err == nil {
			return errors.New(e.RecNotAdded("cxzvfdfasd", t.RecordName()))
		} else {
			return errors.New(e.RecAddErr("jfhgkeytg", t.RecordName()+err.Error()))
		}
	}
}

func (t *EthBlock) EditaRow(y *locals.SyncController) error {

	SyncEditaRowDefault(y, t)
	if affected, err := SyncUpdateQry(y, t.Id).Update(t); affected == 1 && err == nil {
		e.RecEdited("oiryhgsg", t.RecordName())
		return nil
	} else {
		if err == nil { // 같은 컨텐츠의 경우 0 값을 리턴하면서 다음 레코드로 진행
			e.RecNotEdited("liuytrgs", t.RecordName())
			t.Id = 0
			return nil // Error 아님
		} else {
			return errors.New(e.RecEditErr("petresfggs", t.RecordName()+err.Error()))
		}
	}
}

func (t *EthBlock) DelaRow(y *locals.SyncController) error {
	if affected, err := y.Db.ID(t.Id).Delete(t); affected == 1 && err == nil {
		e.RecDeleted("sdfwefavhk", t.RecordName())
		return nil
	} else {
		if err == nil {
			return errors.New(e.RecNotDeleted("lkdfgvfzv", t.RecordName())) // Error간주
		} else {
			return errors.New(e.RecDelErr("potuynbtr", t.RecordName()+err.Error()))
		}
	}
}

type BlockPageRet struct {
	PageVars locals.PageVars
	Page     []EthBlock
}

func (t *BlockPageRet) TableName() string {
	return " Eth_Block "
}

func (t *BlockPageRet) RecordName() string { //필수
	return "Id of " + e.NumToStr(t.TableName) + " in " + e.TableName(*t) + " "
}

func (t *BlockPageRet) GetPage(y *locals.SyncController) error {

	qry := *y.Db.
		Table("Eth_Block").
		Where(t.PageVars.Query).
		Cols(t.PageVars.Fields).
		Limit(t.PageVars.Limit, t.PageVars.Offset)

	if t.PageVars.Asc != "" {
		qry = *qry.Asc(t.PageVars.Asc)
	}
	if t.PageVars.Desc != "" {
		qry = *qry.Desc(t.PageVars.Desc)
	}

	if cnt, err := qry.FindAndCount(&t.Page); err == nil {
		t.PageVars.QueryCnt = cnt
		e.PageRead("qweopfgbjs", t.TableName())
		return nil
	} else {
		return errors.New(e.PageQryErr("qreplhbdf", t.TableName()+err.Error()))
	}
}
