package top.yeij.cyrene.service

import android.content.Intent
import android.os.Bundle
import android.service.voice.VoiceInteractionService
import android.util.Log
import top.yeij.cyrene.MainActivity
import top.yeij.cyrene.util.Constants

class CyreneVoiceInteractionService : VoiceInteractionService() {

    override fun onCreate() {
        super.onCreate()
        Log.i(TAG, "Service created")
    }

    override fun onReady() {
        super.onReady()
        isActive = true
        getSharedPreferences(PREF_NAME, MODE_PRIVATE)
            .edit().putBoolean(KEY_WAS_ACTIVE, true).apply()
        Log.i(TAG, "Service ready")
    }

    override fun onPrepareToShowSession(args: Bundle, showFlags: Int) {
        Log.i(TAG, "onPrepareToShowSession")
    }

    override fun onShowSessionFailed(args: Bundle) {
        Log.e(TAG, "onShowSessionFailed")
    }

    override fun onLaunchVoiceAssistFromKeyguard() {
        Log.i(TAG, "onLaunchVoiceAssistFromKeyguard")
        val intent = Intent(this, MainActivity::class.java).apply {
            addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            putExtra(Constants.EXTRA_VOICE_ASSIST, true)
        }
        startActivity(intent)
    }

    override fun onShutdown() {
        isActive = false
        super.onShutdown()
        Log.i(TAG, "Service shutdown")
    }

    companion object {
        var isActive: Boolean = false
            private set
        private const val TAG = "CyreneVIS"
        private const val PREF_NAME = "cyrene_assistant"
        private const val KEY_WAS_ACTIVE = "was_assistant_active"

        fun wasEverActive(context: android.content.Context): Boolean {
            return context.getSharedPreferences(PREF_NAME, android.content.Context.MODE_PRIVATE)
                .getBoolean(KEY_WAS_ACTIVE, false)
        }
    }
}
