package ginext

import (
	"github.com/gin-gonic/gin"
	"gogs.mikescher.com/BlackForestBytes/goext/langext"
)

type dataHTTPResponse struct {
	statusCode  int
	data        []byte
	contentType string
	headers     []headerval
	cookies     []cookieval
}

func (j dataHTTPResponse) Write(g *gin.Context) {
	for _, v := range j.headers {
		g.Header(v.Key, v.Val)
	}
	for _, v := range j.cookies {
		g.SetCookie(v.name, v.value, v.maxAge, v.path, v.domain, v.secure, v.httpOnly)
	}
	g.Data(j.statusCode, j.contentType, j.data)
}

func (j dataHTTPResponse) WithHeader(k string, v string) HTTPResponse {
	j.headers = append(j.headers, headerval{k, v})
	return j
}

func (j dataHTTPResponse) WithCookie(name string, value string, maxAge int, path string, domain string, secure bool, httpOnly bool) HTTPResponse {
	j.cookies = append(j.cookies, cookieval{name, value, maxAge, path, domain, secure, httpOnly})
	return j
}

func (j dataHTTPResponse) IsSuccess() bool {
	return j.statusCode >= 200 && j.statusCode <= 399
}

func (j dataHTTPResponse) Statuscode() int {
	return j.statusCode
}

func (j dataHTTPResponse) BodyString(*gin.Context) *string {
	return langext.Ptr(string(j.data))
}

func (j dataHTTPResponse) ContentType() string {
	return j.contentType
}

func (j dataHTTPResponse) Headers() []string {
	return langext.ArrMap(j.headers, func(v headerval) string { return v.Key + "=" + v.Val })
}

func Data(sc int, contentType string, data []byte) HTTPResponse {
	return &dataHTTPResponse{statusCode: sc, contentType: contentType, data: data}
}