package services

import (
	"fmt"
	"sync"

	analyzer "gitlab.ost.ch/marketminds/marketminds/pkg/analyze"
	datasql "gitlab.ost.ch/marketminds/marketminds/pkg/data/sql"
	"gitlab.ost.ch/marketminds/marketminds/pkg/entity"
	rss "gitlab.ost.ch/marketminds/marketminds/pkg/rss"
)

func (s *Service) ImportNewsItems() error {
	session := datasql.NewSqlRepository(s.SqlInstance)
	newsChannels, err := session.GetAllNewsChannels()

	if err != nil {
		return fmt.Errorf("Error creating db connection:", err)
	}

	var wg sync.WaitGroup

	for _, newsChannel := range newsChannels {
		wg.Add(1)

		parser := rss.NewParser(s.SqlInstance)

		go func(channel *entity.NewsChannel) {
			defer wg.Done()
			parser.Parse(channel)
		}(newsChannel)
	}

	wg.Wait()

	return nil
}

func (s *Service) ImportSentimentResults() error {
	session := datasql.NewSqlRepository(s.SqlInstance)

	newsItems, err := session.GetFirst50NewsItemsWithoutSentimentResult()
	if err != nil {
		return fmt.Errorf("Error getting news items without sentiment result:", err)
	}

	analyzer := analyzer.NewAnalyzer(session)

	conn, err := analyzer.BuildConnection()
	if err != nil {
		return err
	}
	defer conn.Close()

	for _, newsItem := range newsItems {
		err := analyzer.AnalyzeSentimentResult(newsItem)
		if err != nil {
			fmt.Println("Error analyzing sentiment result:", err)
			break
		}
	}

	return nil
}

func (s *Service) ImportNERResults() error {
	session := datasql.NewSqlRepository(s.SqlInstance)

	newsItems, err := session.GetFirst50NewsItemsWithoutNERResult()
	if err != nil {
		return fmt.Errorf("Error getting news items without NER result:", err)
	}

	analyzer := analyzer.NewAnalyzer(session)

	conn, err := analyzer.BuildConnection()
	if err != nil {
		return err
	}
	defer conn.Close()

	for _, newsItem := range newsItems {
		err := analyzer.AnalyzeNERResult(newsItem)
		if err != nil {
			fmt.Println("Error analyzing NER result:", err)
			break
		}
	}

	return nil
}
