package controllers_table

import (
	"encoding/json"
	"net/http"
	"syncscan-go/controllers"
	"syncscan-go/locals"
	models_table "syncscan-go/models/table"

	"github.com/dabory/abango-rest"
	"github.com/labstack/echo/v4"
)

type BlockPickReq struct {
	Page []models_table.EthBlock
}

type BlockActReq struct {
	Page []models_table.EthBlock
}

func BlockPick(c echo.Context) error {

	v := c.Get("receiver").(BlockPickReq)
	y := c.Get("abango").(abango.Controller)

	vRet := &struct {
		Page []models_table.EthBlock
	}{}

	for _, row := range v.Page {
		if err := row.GetaRow(&y); err != nil {
			return c.String(604, err.Error())
		}
		vRet.Page = append(vRet.Page, row)
	}

	ret, _ := json.Marshal(vRet)
	return c.JSONBlob(http.StatusOK, ret)
}

func BlockAct(c echo.Context) error {

	v := c.Get("receiver").(BlockActReq)
	y := c.Get("abango").(abango.Controller)

	// var msg string
	// var accErr error
	vRet := &locals.IdPageBase{}
	vIdRet := &locals.IdBase{}

	sess := y.Db.NewSession()
	defer sess.Close()
	if err := sess.Begin(); err == nil {
		for _, row := range v.Page {

			if row.Id == 0 {
				if err := row.AddaRow(&y); err != nil {
					sess.Rollback()
					return c.String(603, err.Error())
				}
			} else if row.Id > 0 {
				if err := row.EditaRow(&y); err != nil {
					sess.Rollback()
					return c.String(605, err.Error())
				}
			} else if row.Id < 0 {
				row.Id = -row.Id
				if err := row.DelaRow(&y); err != nil {
					sess.Rollback()
					return c.String(606, err.Error())
				}
			}
			vIdRet.Id = row.Id
			vRet.Page = append(vRet.Page, *vIdRet)
		}
	} else {
		return c.String(608, "Transaction Action Failed")
	}

	if err := sess.Commit(); err != nil {
		return c.String(608, "Transaction Commit Failed")
	}

	ret, _ := json.Marshal(vRet)
	return c.JSONBlob(http.StatusOK, ret)
}

func BlockPage(c echo.Context) error {

	v := c.Get("receiver").(controllers.CommonPageReq)
	y := c.Get("abango").(abango.Controller)

	vRet := &struct {
		models_table.BlockPageRet
	}{}

	vRet.PageVars = v.PageVars
	if err := vRet.GetPage(&y); err != nil {
		return c.String(607, err.Error())
	}

	ret, _ := json.Marshal(vRet)
	return c.JSONBlob(http.StatusOK, ret)
}
