package com.atmob.keyboard_android.keyboard.ext

import android.content.Intent
import android.inputmethodservice.InputMethodService
import androidx.annotation.CallSuper
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.ServiceLifecycleDispatcher
import androidx.lifecycle.ViewModelStore
import androidx.lifecycle.ViewModelStoreOwner

/**
 * 拓展InputMethodService，支持Jetpack组件的Lifecycle生命周期组件，参考自LifecycleService，并同时实现了ViewModelStoreOwner，支持使用ViewModel
 */
open class InputMethodLifecycleService() :
    InputMethodService(), LifecycleOwner, ViewModelStoreOwner {
    private val dispatcher = ServiceLifecycleDispatcher(this)

    // 实现 ViewModelStoreOwner
    override val viewModelStore: ViewModelStore
        get() = ViewModelStore()

    override val lifecycle: Lifecycle
        get() = dispatcher.lifecycle

    @CallSuper
    override fun onCreate() {
        dispatcher.onServicePreSuperOnCreate()
        super.onCreate()
    }

    // onBind()方法，被InputMethodService类，修饰为final，无法被重写，所以只能重写该方法来代替
    override fun onCreateInputMethodInterface(): AbstractInputMethodImpl? {
        dispatcher.onServicePreSuperOnBind()
        return super.onCreateInputMethodInterface()
    }

//    @CallSuper
//    override fun onBind(intent: Intent): IBinder? {
//        dispatcher.onServicePreSuperOnBind()
//        return null
//    }

    @Deprecated("Deprecated in Java")
    @Suppress("DEPRECATION")
    @CallSuper
    override fun onStart(intent: Intent?, startId: Int) {
        dispatcher.onServicePreSuperOnStart()
        super.onStart(intent, startId)
    }

    // this method is added only to annotate it with @CallSuper.
    // In usual Service, super.onStartCommand is no-op, but in LifecycleService
    // it results in dispatcher.onServicePreSuperOnStart() call, because
    // super.onStartCommand calls onStart().
    @CallSuper
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return super.onStartCommand(intent, flags, startId)
    }

    @CallSuper
    override fun onDestroy() {
        dispatcher.onServicePreSuperOnDestroy()
        // 清理ViewModel
        viewModelStore.clear()
        super.onDestroy()
    }
}