//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 db

import (
	"errors"
	"github.com/pocketbase/dbx"
	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/daos"
	"github.com/pocketbase/pocketbase/models"
	"htwkalender/data-manager/model"
	"time"
)

func SaveFeed(feed model.Feed, collection *models.Collection, app *pocketbase.PocketBase) (*models.Record, error) {
	record := models.NewRecord(collection)
	record.Set("modules", feed.Modules)
	err := app.Dao().SaveRecord(record)

	if err != nil {
		return nil, err
	}
	return record, nil
}

func FindFeedByToken(app *pocketbase.PocketBase, token string) (*model.Feed, error) {

	record, err := app.Dao().FindRecordById("feeds", token)

	if err != nil {
		return nil, err
	}

	var feed model.Feed
	feed.Modules = record.GetString("modules")
	feed.Retrieved = record.GetDateTime("retrieved")

	//update retrieved time
	record.Set("retrieved", time.Now())

	err = app.Dao().SaveRecord(record)

	return &feed, err
}

func DeleteFeed(db *daos.Dao, feedId string) error {

	sqlResult, err := db.DB().Delete("feeds", dbx.NewExp("id = {:id}", dbx.Params{"id": feedId})).Execute()
	var deletedRows int64
	if sqlResult != nil {
		deletedRows, _ = sqlResult.RowsAffected()
	}

	if err != nil {
		return err
	} else {
		if deletedRows == 0 {
			return errors.New("No feed with id " + feedId + " found")
		} else {
			return nil
		}
	}
}

func GetAllFeeds(db *daos.Dao) ([]model.Feed, error) {
	var feeds []model.Feed
	err := db.DB().Select("*").From("feeds").All(&feeds)
	if err != nil {
		return nil, err
	}
	return feeds, nil
}
