package dabory

import (
	"kkscrap-go/model"
	"log"
	"regexp"
	"strconv"
	"strings"

	util "kkscrap-go/controllers/scraper/util"

	"github.com/PuerkitoBio/goquery"
)

func Parse(body string, item *model.ItemInfo) {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(body))
	util.CheckError(err)
	doc.Find("meta").Each(func(i int, s *goquery.Selection) {
		v, _ := s.Attr("name")
		if v == "SolutionType" {
			item.SolutionName = model.SolutionType(s.AttrOr("content", ""))
		} else if v == "email" {
			item.Emails = append(item.Emails, s.AttrOr("content", ""))
		}
	})

	item.ItemCategory = doc.Find(".dbr-item-category").Text()
	item.ItemName = doc.Find(".dbr-item-name").Text()
	item.BrandName = doc.Find(".dbr-brand-name").Text()
	str := doc.Find(".dbr-sales-price").Text()
	str = strings.ReplaceAll(str, ",", "")
	str = strings.ReplaceAll(str, "원", "")
	str = strings.TrimSpace(str)
	p, err := strconv.ParseInt(str, 10, 64)
	if err != nil {
		p = 0
		log.Println(str, err)
	}
	item.SalesPrice = float32(p)
	item.OriginDesc, err = doc.Find(".dbr-origin-desc").Html()
	util.CheckError(err)

	item.Images = append(item.Images, doc.Find(".dbr-image-preview").AttrOr("src", ""))

	re := regexp.MustCompile(`-\d+x\d+\.`)
	doc.Find(".dbr-image-thumb").Each(func(i int, s *goquery.Selection) {
		img := s.AttrOr("src", "")
		img = re.ReplaceAllString(img, ".")
		item.Images = append(item.Images, img)
	})

	opt := model.Option{}
	doc.Find(".dbr-option1 > option").Each(func(i int, selection *goquery.Selection) {
		opt.Choices = append(opt.Choices, model.Choice{
			Name: selection.Text(),
		})
	})
	item.Options = append(item.Options, opt)

	opt = model.Option{}
	doc.Find(".dbr-option2 > option").Each(func(i int, selection *goquery.Selection) {
		opt.Choices = append(opt.Choices, model.Choice{
			Name: selection.Text(),
		})
	})
	item.Options = append(item.Options, opt)

	return
}

func getCurrency(body string) string {
	reg, _ := regexp.Compile("var gdCurrencyCode = '(.*)';")
	ss := reg.FindStringSubmatch(body)
	return ss[1]
}

func getPrice(body string) float32 {
	reg, _ := regexp.Compile("'setGoodsPrice'[ ]*:[ ]*'(.*)'")
	ss := reg.FindStringSubmatch(body)
	return util.GetFloat32(ss[1])
}
