package main

import (
	"fmt"
	"log"

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

func main() {
	var cfg config.Config
	var cr coronafana.Coronafana
	var err error

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

	db, err := sqlx.Connect("mysql",
		fmt.Sprintf("%s:%s@tcp(%s)/%s",
			cfg.DbUsername,
			cfg.DbPassword,
			cfg.DbHostname,
			cfg.DbName))
	if err != nil {
		log.Fatalln(err)
	}

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

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

	tr, dialer, dialerctx, err := network.InitTorSession()
	if err != nil {
		log.Fatalln(err)
	}
	defer dialerctx()
	defer tr.Close()

	cr, err = coronafana.GetData(cfg, dialer)
	if err != nil {
		log.Fatalln(err)
	}

	err = cr.GetMaxDates(cfg, *db)
	if err != nil {
		log.Fatalln(err)
	}

	// Processes data for 'Global'
	err = cr.InsertGlobalData(cfg, *db)
	if err != nil {
		log.Fatalln(err)
	}

	// Processes data for 'Pays'
	err = cr.InsertPaysData(cfg, *db)
	if err != nil {
		log.Fatalln(err)
	}

}
