package main

import (
	"fmt"
	"log"

	"git.paulbsd.com/paulbsd/qrz/src/config"
	"git.paulbsd.com/paulbsd/qrz/src/qrz"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
)

func main() {
	var config config.Config

	config.GetConfig()

	db, err := sqlx.Connect("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s", config.DbUsername, config.DbPassword, config.DbHostname, config.DbName))

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

	_, err = db.Exec(config.DbSchema)
	if err != nil {
		log.Fatalln(err)
	}

	bodyStr, err := qrz.GetBody(config)
	if err != nil {
		log.Fatalln(err)
	}

	frsPeople, err := qrz.GetFrsEntries(config, bodyStr)
	if err != nil {
		log.Fatalln(err)
	}

	existingQrz, err := qrz.GetCurrentEntries(config, *db)
	if err != nil {
		log.Fatalln(err)
	}

	err = qrz.DiscardExistingEntries(config, &frsPeople, existingQrz)
	if err != nil {
		log.Fatalln(err)
	}

	if len(frsPeople) > 0 {
		err = qrz.InsertFrsEntryToDB(config, *db, frsPeople)
		if err != nil {
			log.Fatalln(err)
		}
	} else {
		fmt.Println("No entry to insert in database")
	}
}
