package com.kdanmobile.reader

import android.annotation.SuppressLint
import com.kdanmobile.kmpdfkit.manager.KMPDFFactory
import com.kdanmobile.kmpdfkit.manager.controller.KMPDFDocumentController
import com.kdanmobile.kmpdfkit.manager.controller.KMPDFSignatureController

class ReaderModel {
    private var filename: String? = null
    var password: String = ""
        private set

    var kmpdfFactory: KMPDFFactory? = null
        private set

    @SuppressLint("StaticFieldLeak")
    var kmpdfDocumentController: KMPDFDocumentController? = null
        private set

    var kmpdfSignatureController: KMPDFSignatureController? = null
        private set

    var onPdfChangedListener: OnPdfChangedListener? = null

    var referenceCount = 0

    @Synchronized
    fun initKMPDFFactory(kmpdfFactory: KMPDFFactory?, filename: String?, password: String = "") {

        this.kmpdfFactory?.run {
            destroy()
        }

        this.kmpdfFactory = kmpdfFactory
        this.filename = filename
        this.password = password
    }

    fun initKMPDFDocumentController() {
        kmpdfDocumentController = kmpdfFactory?.getController(KMPDFFactory.ControllerType.DOCUMENT) as KMPDFDocumentController
        kmpdfSignatureController = kmpdfFactory?.getController(KMPDFFactory.ControllerType.SIGNATURE) as KMPDFSignatureController
    }

    @Synchronized
    fun destroy() {
        filename = null
        password = ""
        kmpdfFactory?.onDestroy()
        kmpdfFactory = null
        kmpdfDocumentController = null
        kmpdfSignatureController = null
        onPdfChangedListener = null
        referenceCount = 0
    }

    fun register() {
        referenceCount++
    }

    fun unregister() {
        referenceCount--
        if (referenceCount == 0) {
            destroy()
        }
    }
}