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.getAnnouncements
import de.sebse.fuplanner2.database.*
import de.sebse.fuplanner2.utils.Notifications
import de.sebse.fuplanner2.utils.UpdateResult
import de.sebse.fuplanner2.whiteboard.Whiteboard
import de.sebse.fuplanner2.whiteboard.getAnnouncements

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

    companion object {
        suspend fun work(appCtx: Context, database: AppDatabase, user: User, course: Course): UpdateResult<Announcement> {
            return Whiteboard.getAnnouncements(appCtx, database, user, course)
                    .merge(Blackboard.getAnnouncements(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
    }
}
