/**
 * ProjectLaogai
 *
 * Copyright 2019-2020  <seil0@mosad.xyz>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 *
 */

package org.mosad.seil0.projectlaogai.worker

import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.Worker
import androidx.work.WorkerParameters
import kotlinx.coroutines.runBlocking
import org.mosad.seil0.projectlaogai.MainActivity
import org.mosad.seil0.projectlaogai.R
import org.mosad.seil0.projectlaogai.controller.GradesController
import org.mosad.seil0.projectlaogai.controller.cache.CacheController
import org.mosad.seil0.projectlaogai.controller.preferences.EncryptedPreferences
import org.mosad.seil0.projectlaogai.util.NotificationUtils
import org.mosad.seil0.projectlaogai.util.NotificationUtils.Companion.CHANNEL_ID_GRADES

class GradesUpdateWorker(val context: Context, params: WorkerParameters): Worker(context, params) {

    override fun doWork(): Result {

        // check if credentials are present, if not do nothing
        val credentials = EncryptedPreferences.readCredentials(context)
        if (credentials.first.isEmpty() || credentials.second.isEmpty()) {
            return Result.success()
        }

        val notificationIdChecking = NotificationUtils.getId()
        val builderChecking = NotificationCompat.Builder(context, CHANNEL_ID_GRADES)
            .setSmallIcon(R.drawable.ic_grading_black_24dp)
            .setContentTitle(context.getString(R.string.notification_grades))
            .setContentText(context.getString(R.string.notification_grades_updating_desc))
            .setNotificationSilent()
        NotificationManagerCompat.from(context).apply {
            notify(notificationIdChecking, builderChecking.build())
        }

        // get old grades
        val oldGrades = CacheController(context).readGrades()

        // get update from qispos
        runBlocking { CacheController.updateGrades(context).join() }
        val newGrades = CacheController(context).readGrades()

        // check for changes
        val diff = GradesController().diffGrades(oldGrades, newGrades)

        // show message
        if (diff.isNotEmpty()) {
            val text = if (diff.size < 2) {
                context.getString(R.string.notification_grades_single_desc, diff.first().name)
            } else {
                context.getString(R.string.notification_grades_multiple_desc, diff.first().name, (diff.size - 1))
            }

            val intent = Intent(context, MainActivity::class.java).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
                action = context.getString(R.string.intent_action_gradesFragment)
            }

            val pendingIntent: PendingIntent = PendingIntent.getActivity(context, 0, intent, 0)

            val builder = NotificationCompat.Builder(context, CHANNEL_ID_GRADES)
                .setSmallIcon(R.drawable.ic_grading_black_24dp)
                .setContentTitle(context.getString(R.string.notification_grades))
                .setContentText(text)
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)

            // if there are multiple subjects, use BigText
            if (diff.size > 1)
                builder.setStyle(NotificationCompat.BigTextStyle().bigText(text))

            NotificationManagerCompat.from(context).apply {
                notify(NotificationUtils.getId(), builder.build())
            }
        }

        // remove scanning notification
        NotificationManagerCompat.from(context).apply {
            cancel(notificationIdChecking)
        }

        return Result.success()
    }



}