package com.kdanmobile.reader

import android.net.Uri
import java.util.concurrent.ConcurrentHashMap

class ReaderModelManager {
    private val map = ConcurrentHashMap<Uri, ReaderModel>()
    private val counter = ConcurrentHashMap<Uri, Int>()

    @Synchronized fun get(uri: Uri): ReaderModel {
        val readerModel = map.getOrPut(uri) {
            val readerModel = ReaderModel()
            counter[uri] = 0
            return@getOrPut readerModel
        }
        counter[uri]?.also {
            counter[uri] = it + 1
        }
        return readerModel
    }

    @Synchronized fun release(uri: Uri) {
        counter[uri]?.also {
            if (it > 1) {
                counter[uri] = it - 1
            } else {
                map[uri]?.destroy()
                map.remove(uri)
                counter.remove(uri)
            }
        }
    }
}