package com.wirelesstextsyncer.wireless_text_syncer_android

import android.app.PendingIntent
import android.content.ComponentName
import android.content.Intent
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import android.util.Log

class QuickSendTileService : TileService() {
    override fun onStartListening() {
        super.onStartListening()
        Log.d("WTS", "QuickSendTileService onStartListening")
        refreshTile()
    }

    override fun onClick() {
        super.onClick()
        Log.d("WTS", "QuickSendTileService onClick")
        val intent = Intent(this, QuickSendActivity::class.java)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
            val pendingIntent = PendingIntent.getActivity(
                this,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
            )
            startActivityAndCollapse(pendingIntent)
        } else {
            @Suppress("DEPRECATION")
            startActivityAndCollapse(intent)
        }
    }

    private fun refreshTile() {
        val tile = qsTile ?: return
        val state = ConnectionService.stateMap()
        val connected = state["connected"] as? Boolean ?: false
        tile.label = "文本同步"
        tile.subtitle = if (connected) "已连接" else "未连接"
        tile.state = if (connected) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
        tile.updateTile()
    }

    companion object {
        fun requestTileRefresh() {
            Log.d("WTS", "QuickSendTileService requestTileRefresh")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                try {
                    requestListeningState(
                        WirelessTextSyncerApplicationHolder.context,
                        ComponentName(WirelessTextSyncerApplicationHolder.context, QuickSendTileService::class.java)
                    )
                } catch (exception: Exception) {
                    Log.e("WTS", "requestListeningState failed", exception)
                }
            }
        }
    }
}
