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.database.AppDatabase
import de.sebse.fuplanner2.database.Course
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

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

    companion object {
        suspend fun work(appCtx: Context, database: AppDatabase, user: User, courseId: Long? = null): UpdateResult<Course> {
            return if (courseId != null) {
                Whiteboard.getCourse(appCtx, database, user, courseId)
                    .merge(Blackboard.getCourse(appCtx, database, user, courseId))
            } else {
                Whiteboard.getCourses(appCtx, database, user)
                    .merge(Blackboard.getCourses(appCtx, database, user))
            }
        }
    }

    override suspend fun doActualWork(database: AppDatabase, account: Account, user: User): Data {
        val courseId = inputData.getLong(KEY_COURSE_ID, -1)
            .let { if (it == -1L) null else it }
        val updates = work(applicationContext, database, user, courseId)
        val latestSemester = database.courseDao().getLatestSemesterName()
        updates.added.forEach {
            if (it.isSummerSemester == latestSemester.semester && it.year == latestSemester.year) {
                EventWorker.work(applicationContext, database, user, it)
            }
        }
        Notifications.courseUpdates(updates, database,  applicationContext)
        return inputData
    }
}
