package lib

import (
	"fmt"
	"log"
	"os"
	"strings"
	"time"
)

func getConfig() Config {
	return Config{
		WikiBaseURL:         os.Getenv("WIKI_BASE_URL"),
		WikiToken:           os.Getenv("WIKI_TOKEN"),
		WikiContentLimit:    envToInteger("WIKI_CONTENT_LIMIT", 10),
		RedmineBaseURL:      os.Getenv("REDMINE_BASE_URL"),
		RedmineKey:          os.Getenv("REDMINE_KEY"),
		RedmineContentLimit: envToInteger("REDMINE_CONTENT_LIMIT", 10),
		GiteaToken:          os.Getenv("GITEA_TOKEN"),
		GiteaBaseURL:        os.Getenv("GITEA_BASE_URL"),
		GiteaRepos:          strings.Split(os.Getenv("GITEA_REPOS"), ","),
		GiteaContentLimit:   envToInteger("GITEA_CONTENT_LIMIT", 10),
		DiscordWebhook:      os.Getenv("DISCORD_WEBHOOK"),
		DiscordFake:         os.Getenv("DISCORD_FAKE") == "true",
		Interval:            time.Duration(envToInteger("INTERVAL_MINUTES", 5)) * time.Minute,
	}
}

func getFetchers(config *Config, cache *Cache) []Fetcher {
	return []Fetcher{
		&GiteaFetcher{
			BaseFetcher: BaseFetcher{
				BaseURL:      config.GiteaBaseURL,
				Token:        config.GiteaToken,
				Cache:        cache,
				ContentLimit: config.GiteaContentLimit,
			},
			Repos: config.GiteaRepos,
		},
		&WikiFetcher{
			BaseFetcher: BaseFetcher{
				BaseURL:      config.WikiBaseURL,
				Token:        config.WikiToken,
				Cache:        cache,
				ContentLimit: config.WikiContentLimit,
			},
		},
		&RedmineFetcher{
			BaseFetcher: BaseFetcher{
				BaseURL:      config.RedmineBaseURL,
				Token:        config.RedmineKey,
				Cache:        cache,
				ContentLimit: config.RedmineContentLimit,
			},
		},
	}
}

func getCache() Cache {
	cache := *NewCache()
	cache.Load()
	return cache
}

func getDiscordSender(config Config) DiscordSender {
	return DiscordSender{
		Webhook: config.DiscordWebhook,
		Fake:    config.DiscordFake,
	}
}

func getMessages(fetchers []Fetcher) []string {
	messages := []string{}
	for _, fetcher := range fetchers {
		entries := fetcher.Fetch()
		for _, entry := range entries {
			messages = append(messages, fmt.Sprintf("[%s](%s)", entry.Title, entry.URL))
		}
	}
	return messages
}

func Runner() {
	loadEnv()
	config := getConfig()
	cache := getCache()
	discord_sender := getDiscordSender(config)
	fetchers := getFetchers(&config, &cache)
	for {
		log.Println("Run updater...")
		messages := getMessages(fetchers)
		discord_sender.SendBatch(messages)
		cache.Save()
		time.Sleep(config.Interval)
	}
}
