package controllers_join

import (
	"encoding/json"
	"fmt"
	"net/http"
	controllers_func "syncscan-go/controllers/func"
	models_join "syncscan-go/models/join"
	models_table "syncscan-go/models/table"

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

type ListType1BookReq struct {
	Book []ListType1PageReq
}

func ListType1Book(c echo.Context) error {

	v := c.Get("receiver").(ListType1BookReq)
	y := c.Get("abango").(abango.Controller)
	fmt.Println(len(v.Book))

	vRet := &models_join.ListType1BookRet{}
	vPgRet := &models_join.ListType1PageRet{}
	vEmptyPage := &struct {
		Page []models_table.DbtListType1
	}{}

	for _, row := range v.Book {

		vPgRet.QueryVars = row.QueryVars
		vPgRet.SetupVars = row.SetupVars
		vPgRet.ListType1Vars = row.ListType1Vars
		vPgRet.PageVars = row.PageVars
		vPgRet.Page = vEmptyPage.Page

		r := c.Request().URL.Path
		sqlDir := ""
		if r == "/list-type1-book" {
			sqlDir = "list"
		} else if r == "/search-type1-book" { //이건 뭐지 ?
			sqlDir = "search"
		}

		if vPgRet.ListType1Vars.IsDownloadList == false {
			if err := vPgRet.GetListType1PagePlain(&y, sqlDir); err != nil {
				return c.String(607, err.Error())
			}
		} else if vPgRet.ListType1Vars.IsDownloadList == true {
			if err := vPgRet.GetListType1PageTmp(&y, sqlDir); err != nil {
				return c.String(607, err.Error())
			}
		}

		if len(vPgRet.SetupVars) != 0 {
			if err := controllers_func.SetupJsonArrayGet(&y, vPgRet); err != nil {
				return c.String(607, err.Error())
			}
		}

		vRet.Book = append(vRet.Book, *vPgRet)
	}

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