package de.sebse.fuplanner2.worker

import android.accounts.Account
import android.content.Context
import androidx.work.Data
import androidx.work.WorkerParameters
import de.sebse.fuplanner2.blackboard.Blackboard
import de.sebse.fuplanner2.blackboard.getCourse
import de.sebse.fuplanner2.blackboard.getCourses
import de.sebse.fuplanner2.blackboard.getEvents
import de.sebse.fuplanner2.database.AppDatabase
import de.sebse.fuplanner2.database.Course
import de.sebse.fuplanner2.database.Event
import de.sebse.fuplanner2.database.User
import de.sebse.fuplanner2.utils.Notifications
import de.sebse.fuplanner2.utils.UpdateResult
import de.sebse.fuplanner2.utils.console
import de.sebse.fuplanner2.whiteboard.Whiteboard
import de.sebse.fuplanner2.whiteboard.getCourse
import de.sebse.fuplanner2.whiteboard.getCourses
import de.sebse.fuplanner2.whiteboard.getEvents

class EventWorker(context: Context, params: WorkerParameters) : AbstractAccountWorker(context, params) {

    companion object {
        suspend fun work(appCtx: Context, database: AppDatabase, user: User, course: Course): UpdateResult<Event> {
            return Whiteboard.getEvents(appCtx, database, user, course)
                    .merge(Blackboard.getEvents(appCtx, database, user, course))
        }
    }

    override suspend fun doActualWork(database: AppDatabase, account: Account, user: User): Data {
        inputData.getLong(KEY_COURSE_ID, -1)
            .let { if (it == -1L) null else it }
            ?.let {
                database.courseDao().getCourseById2(it)
            }
            ?.let {
                Notifications.courseUpdates(work(applicationContext, database, user, it), database,  applicationContext)
            }
        return inputData
    }
}
