package pages

import (
	"database/sql"
	"fmt"
	"log"
	"net/http"

	"github.com/PuerkitoBio/goquery"
	matrixbot "roese.dev/matrix-development-lauge/matrix-bot"
	"roese.dev/matrix-development-lauge/modules/config"
	"roese.dev/matrix-development-lauge/modules/database"
)

func School() {
	res, err := http.Get("https://radko-stoeckl-schule.de")

	if err != nil {
		log.Println("Failed to get response from radko stoeckl schule page")
		return
	}

	defer res.Body.Close()

	if res.StatusCode != 200 {
		log.Fatal("status code")
	}

	doc, err := goquery.NewDocumentFromReader(res.Body)

	if err != nil {
		log.Fatal(err)
	}

	firstListItem := doc.Find(".news-teaser ul li:first-of-type")

	latest_page_title := firstListItem.Find("a h4").Text()

	db := database.GetDatabase()

	defer db.Close()

	stmt, err := db.Prepare("SELECT page_title FROM pages WHERE page_id = ?")

	if err != nil {
		log.Fatal(err)
	}

	defer stmt.Close()

	var pageTitle string

	send := false

	err = stmt.QueryRow("school").Scan(&pageTitle)

	if err == sql.ErrNoRows {
		_, err = db.Exec(fmt.Sprintf("INSERT INTO pages(page_id, page_title) values('school', '%s')", latest_page_title))

		if err != nil {
			log.Fatal(err)
		}

		send = true
	}

	if err != nil {
		log.Fatal(err)
	}

	if pageTitle != latest_page_title {
		_, err = db.Exec(fmt.Sprintf("UPDATE pages SET page_title = '%s' WHERE page_id = 'school'", latest_page_title))

		if err != nil {
			log.Fatal(err)
		}

		send = true
	}

	if send {
		text := firstListItem.Find("a .news-summary").Text()

		url := firstListItem.Find("a").AttrOr("href", "")

		log.Println("header", latest_page_title, "text", text, "url", url)

		matrixbot.SendMessage(config.Cfg.Pages[0].RoomID, "Radko-Stöckl-Schule - Aktuelles", latest_page_title, text, "https://www.radko-stoeckl-schule.de"+url)
	}
}
