package com.doctate.watch.complication

import android.app.PendingIntent
import android.content.Intent
import androidx.wear.watchface.complications.data.ComplicationData
import androidx.wear.watchface.complications.data.ComplicationType
import androidx.wear.watchface.complications.data.PlainComplicationText
import androidx.wear.watchface.complications.data.ShortTextComplicationData
import androidx.wear.watchface.complications.datasource.ComplicationRequest
import androidx.wear.watchface.complications.datasource.SuspendingComplicationDataSourceService
import com.doctate.watch.presentation.MainActivity
import com.doctate.watch.presentation.NavCommand

/**
 * Fast-launch Complication for the Doctate app. Always reports the same label;
 * tap opens the case list. Doctors place it on their watchface manually.
 */
class DoctateComplicationService : SuspendingComplicationDataSourceService() {

    override fun getPreviewData(type: ComplicationType): ComplicationData? =
        when (type) {
            ComplicationType.SHORT_TEXT -> buildShortText(previewOnly = true)
            else -> null
        }

    override suspend fun onComplicationRequest(request: ComplicationRequest): ComplicationData? =
        when (request.complicationType) {
            ComplicationType.SHORT_TEXT -> buildShortText(previewOnly = false)
            else -> null
        }

    private fun buildShortText(previewOnly: Boolean): ShortTextComplicationData {
        val text = PlainComplicationText.Builder("Doctate").build()
        val builder = ShortTextComplicationData.Builder(
            text = text,
            contentDescription = PlainComplicationText.Builder("Open Doctate case list").build(),
        )
        if (!previewOnly) {
            builder.setTapAction(buildTapIntent())
        }
        return builder.build()
    }

    private fun buildTapIntent(): PendingIntent {
        val intent = Intent(this, MainActivity::class.java).apply {
            putExtra(NavCommand.EXTRA_OPEN, NavCommand.OPEN_LIST)
        }
        return PendingIntent.getActivity(
            this,
            0,
            intent,
            PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT,
        )
    }
}
