package flashscore

import (
	"fmt"
	"regexp"
	"strconv"

	"github.com/PuerkitoBio/goquery"
)

func parseOdds1x2(tableSelection *goquery.Selection) (offers []Winner3Way, err error) {
	tdList := tableSelection.Find("td.bookmaker")

	for idx := 0; idx < tdList.Length(); idx++ {
		//tdList.Each(func(idx int, tdSelection *goquery.Selection) {
		var offer Winner3Way
		//.Get(0).Data //.Html()
		//fmt.Printf("%s\n", txt)
		//fmt.Printf("%v\n", tdSelection)
		//tdSelection.Get(0)
		//tdSelection.Next()

		tdSelection := tdList.Eq(idx)

		offer.Bookmaker, err = getBookmaker(tdSelection)
		if err != nil {
			return
		}

		priceTd := tdSelection.Next()

		offer.Home, err = getPrice(priceTd)
		if err != nil {
			err = fmt.Errorf("get home price: %s", err)
			return
		}

		priceTd = priceTd.Next()

		offer.Draw, err = getPrice(priceTd)
		if err != nil {
			err = fmt.Errorf("get draw price: %s", err)
			return
		}

		priceTd = priceTd.Next()

		offer.Away, err = getPrice(priceTd)
		if err != nil {
			err = fmt.Errorf("get away price: %s", err)
			return
		}

		offers = append(offers, offer)
	}
	return
}

// /bookmaker/17/
var reBookmakerID = regexp.MustCompile(`/bookmaker/(\d+)`)

func getBookmaker(tdSelection *goquery.Selection) (bookmakerID int, err error) {
	aSelection := tdSelection.Find("a")
	if aSelection.Length() == 0 {
		err = fmt.Errorf("<a> tag not found in bookmaker's <td>")
		return
	}

	//a := aSelection.Get(0)
	href, exists := aSelection.Eq(0).Attr("href")
	if !exists {
		err = fmt.Errorf("href attr not found in <a> tag")
		return
	}

	// /fmt.Printf("href: %s\n", href)

	groups := reBookmakerID.FindStringSubmatch(href)
	if len(groups) != 2 {
		err = fmt.Errorf("BookmakerID in href not found. Regexp result: %q", groups)
		return
	}

	bookmakerID, _ = strconv.Atoi(groups[1])
	return
}

func getPrice(tdSelection *goquery.Selection) (price float64, err error) {
	if tdSelection == nil {
		err = fmt.Errorf("<td> tag selection is nil")
		return
	}

	spanSelection := tdSelection.Find("span")
	if spanSelection.Length() == 0 {
		err = fmt.Errorf("<span> not found in <td>")
		return
	}

	span := spanSelection.Get(0)
	priceStr := span.FirstChild.Data // fix - if not text node

	price, err = strconv.ParseFloat(priceStr, 64)
	if err != nil {
		err = fmt.Errorf("Parse price: %s; priceStr=%q", err, priceStr)
		return
	}
	return
}
