package com.atmob.keyboard_android.keyboard

import android.inputmethodservice.InputMethodService
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.inputmethod.EditorInfo
import com.atmob.keyboard_android.R
import com.atmob.keyboard_android.keyboard.ext.InputMethodLifecycleService
import com.atmob.keyboard_android.mvvm.ViewModelManager
import com.atmob.keyboard_android.mvvm.viewmodel.KeyboardViewModel
import com.atmob.keyboard_android.util.ClipboardHelper
import com.atmob.keyboard_android.util.KeyboardHolder
import com.atmob.keyboard_android.util.LogUtil

/**
 * 自定义键盘的输入法服务
 */
class CustomKeyboardService : InputMethodLifecycleService(), ICustomKeyboardService,
    ClipboardHelper.OnUserClipboardDataUpdateListener {
    /**
     * 键盘ViewModel
     */
    private val mKeyboardViewModel by lazy {
        ViewModelManager.getKeyboardViewModel(this@CustomKeyboardService)
    }

    override fun onUserClipboardDataUpdate(newText: String) {
        // 剪切板数据更新
        mKeyboardViewModel.updateUserClipboardData(newText)
    }

    override fun onCreate() {
        super.onCreate()
        // 保存输入法Service的实例
        KeyboardHolder.attachKeyboardService(this)
        // 监听用户的剪切板
        ClipboardHelper.registerClipboardListener(this)
    }

    override fun onCreateInputView(): View {
        return layoutInflater.inflate(R.layout.keyboard_layout, null)
    }

    override fun onStartInputView(info: EditorInfo?, restarting: Boolean) {
        super.onStartInputView(info, restarting)
        // 键盘弹起
        LogUtil.d("CustomKeyboardService => onStartInputView()")
    }

    override fun onFinishInputView(finishingInput: Boolean) {
        super.onFinishInputView(finishingInput)
        // 键盘收下
        LogUtil.d("CustomKeyboardService => onFinishInputView()")
    }

    override fun onDestroy() {
        super.onDestroy()
        KeyboardHolder.detachKeyboardService()
        ClipboardHelper.unRegisterClipboardListener(this)
    }

    override fun getKeyboardWindow(): Window {
        return window!!.window!!
    }

    override fun getRootView(): ViewGroup {
        return window.window?.decorView!! as ViewGroup
    }

    override fun getKeyboardViewModel(): KeyboardViewModel {
        return mKeyboardViewModel
    }

//    override fun getLifecycleOwner(): LifecycleOwner {
//        return this
//    }

    override fun asInputMethodService(): InputMethodService {
        return this
    }

    override fun findViewById(viewId: Int): View? {
        return getRootView().findViewById(viewId)
    }
}