//Calendar implementation for the HTWK Leipzig timetable. Evaluation and display of the individual dates in iCal format.
//Copyright (C) 2024 HTWKalender support@htwkalender.de

//This program is free software: you can redistribute it and/or modify
//it under the terms of the GNU Affero General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU Affero General Public License for more details.

//You should have received a copy of the GNU Affero General Public License
//along with this program.  If not, see <https://www.gnu.org/licenses/>.

package feed

import (
	"github.com/pocketbase/pocketbase"
	"htwkalender/data-manager/model"
	database "htwkalender/data-manager/service/db"
	localTime "htwkalender/data-manager/service/functions/time"
	"log/slog"
	"strings"
)

func ClearFeeds(base *pocketbase.PocketBase, months int, clock localTime.Clock) {
	feeds, err := database.GetAllFeeds(base)
	if err != nil {
		slog.Error("CleanFeeds: failed to get all feeds", "error", err)
		return
	}
	for _, feed := range feeds {
		// if retrieved time is older than a half year delete feed
		now := clock.Now()
		feedRetrievedTime := feed.Retrieved.Time()
		timeShift := now.AddDate(0, -months, 0)

		if feedRetrievedTime.Before(timeShift) {
			// delete feed
			feedErr := database.DeleteFeed(base, feed.Id)
			if feedErr != nil {
				slog.Error("CleanFeeds: failed to delete feed: "+feed.Id, "error", feedErr)
			}
		}
	}
}

func CombineEventsInFeed(events model.Events) model.Events {
	// Combine events with the same name, start, end and course
	// check if there are events
	if len(events) > 0 {
		combinedEvents := model.Events{events[0]}

		for i := 1; i < len(events); i++ {
			// check if the event is already in the combinedEvents
			alreadyInCombinedEvents := false

			for j := 0; j < len(combinedEvents); j++ {
				if events[i].Name == combinedEvents[j].Name &&
					events[i].Start == combinedEvents[j].Start &&
					events[i].End == combinedEvents[j].End &&
					events[i].Course == combinedEvents[j].Course {
					alreadyInCombinedEvents = true
					combinedEvents[j].Notes = addNotesIfAlreadyRoomsAdded(events, combinedEvents, j, i)
					combinedEvents[j].Prof = combineProfs(events, i, combinedEvents, j)
					combinedEvents[j].Rooms = combineRooms(events, i, combinedEvents, j)
					break
				}
			}
			if !alreadyInCombinedEvents {
				combinedEvents = append(combinedEvents, events[i])
			}
		}
		return combinedEvents
	}
	return model.Events{}
}

func addNotesIfAlreadyRoomsAdded(events model.Events, combinedEvents model.Events, index2 int, index1 int) string {
	// check if combinedEvents[index2].Rooms string contains comma "," &#44
	if !strings.Contains(combinedEvents[index2].Rooms, ",") {
		return descriptionString(combinedEvents[index2]) + "\n" + descriptionString(events[index1])
	} else {
		return combinedEvents[index2].Notes + "\n" + descriptionString(events[index1])
	}
}

func combineProfs(events model.Events, index1 int, combinedEvents model.Events, index2 int) string {
	// combine the profs
	if events[index1].Prof != "" {
		if combinedEvents[index2].Prof == "" {
			return events[index1].Prof
		} else {
			if !strings.Contains(combinedEvents[index2].Prof, events[index1].Prof) {
				return combinedEvents[index2].Prof + ", " + events[index1].Prof
			}
		}
	}
	return combinedEvents[index2].Prof
}

func descriptionString(event model.Event) string {
	return event.Rooms + " - " + event.Notes + " (" + event.Prof + ")"
}

func combineRooms(events model.Events, index1 int, combinedEvents model.Events, index2 int) string {
	// combine the rooms
	if events[index1].Rooms != "" {
		if combinedEvents[index2].Rooms == "" {
			return events[index1].Rooms
		} else {
			if !strings.Contains(combinedEvents[index2].Rooms, events[index1].Rooms) {
				return combinedEvents[index2].Rooms + ", " + events[index1].Rooms
			}
		}
	}
	return combinedEvents[index2].Rooms
}

func MarkFeedForDeletion(base *pocketbase.PocketBase, feedId string) error {
	return database.MarkForDelete(base, feedId)
}
