package main

import (
	"flag"
	"gitea-page/internal/config"
	git "gitea-page/internal/git"
	"gitea-page/internal/gitea"
	"gitea-page/internal/promote"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"
	"gopkg.in/yaml.v2"
	"net/http"
	"os"
)

func main () {
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
	log.Info().Msg("Start")
	config := readConfig()
	setupSystem(config)

	g := git.GitHandler{}
	g.Config = config

	p := promote.Promote{}
	p.Config = config

	gitea := gitea.GiteaWebhook{}
	gitea.Config = config
	gitea.Git = g
	gitea.Promoter = p

	runHTTPServer(gitea)
}

func setupSystem(config config.GiteaPagesConfig) {
	_, err := os.Stat(config.RootPath)
	if os.IsNotExist(err) {
		log.Fatal().Str("Root Path", config.RootPath).Msg("Root Path not exists")
	}
}

func runHTTPServer(gitea gitea.GiteaWebhook) {
	http.HandleFunc("/gitea", gitea.WebhookEndpoint)
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		writer.Write([]byte("Ok"))
	})

	err := http.ListenAndServe(":3000", nil)
	if err != nil {
		log.Warn().Err(err).Msg("Error while running http servre")
	}
}

func readConfig() config.GiteaPagesConfig {
	var configFile string
	flag.StringVar(&configFile, "c", "/etc/gitea-page/config.yml", "Specify configfile, default /etc/gitea-page/config.yml")
	flag.Parse()

	ymlFile, err := os.ReadFile(configFile)
	if err != nil {
		log.Fatal().Str("configFile", configFile).Err(err).Msg("Cant read config file")
	}

	config := config.GiteaPagesConfig{}

	yaml.Unmarshal(ymlFile, &config)
	log.Debug().Str("configFile", configFile).Interface("config", config).Msg("Read config from File")

	return config
}

func updateCallback(owner, name, url string) {

}