package controllers_join

import (
	"encoding/json"
	models_table "kkscrap-go/models/table"
	"net/http"

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

type ListType1UploadReq struct {
	// Page          []models_table.DbtUploadType1
	Page []models_table.DbtListType1
}

func ListType1Upload(c echo.Context) error {

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

	vRet := &struct {
		ListToken string
	}{}

	sess := y.Db.NewSession()
	defer sess.Close()

	// tmpTable := "dbt_upload_type1"
	// y.Db.Exec("delete from " + tmpTable + " where created_on > 0")
	listToken := e.RandString(10)
	if err := sess.Begin(); err == nil {
		for _, row := range v.Page {
			row.Id = 0
			row.ListToken = listToken
			if err := row.AddaRow(&y); err != nil {
				sess.Rollback()
				return c.String(603, err.Error())
			}
		}
	} else {
		return c.String(608, "Transaction Action Failed")
	}

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

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