package me.sdidev.simpleroutetracker.snapshot

import android.content.Context
import android.content.ContextWrapper
import android.graphics.Bitmap
import io.reactivex.Single
import me.sdidev.simpleroutetracker.App
import me.sdidev.simpleroutetracker.core.Route
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import java.io.FileOutputStream
import javax.inject.Inject


const val ROUTES_DIRECTORY_NAME = "routes"
const val QUALITY = 65

class ExternalStorageSnapshotManager @Inject constructor(applicationContext: App): SnapshotManager {

    private val logger: Logger = LoggerFactory.getLogger(ExternalStorageSnapshotManager::class.java)
    private val routesDirectory: File = ContextWrapper(applicationContext).getDir(ROUTES_DIRECTORY_NAME, Context.MODE_PRIVATE)

    override fun store(storeRequest: StoreRequest): Single<Image> {
        return Single.fromCallable {
            val pathToSnapshot = fileForRoute(storeRequest.route)

            logger.debug("path to snapshot: {}", pathToSnapshot)

            val fileOutputStream = FileOutputStream(pathToSnapshot)
            storeRequest.mapSnapshot.compress(Bitmap.CompressFormat.PNG, QUALITY, fileOutputStream)
            fileOutputStream.close()

            logger.debug("saved: {}", pathToSnapshot)

            Image(pathToSnapshot.absolutePath)
        }
    }

    override fun restore(route: Route): Single<Image> {
        return Single.fromCallable {
            val snapshotFile = fileForRoute(route)
            if (snapshotFile.exists()) {
                logger.debug("restored shapshot: {}", snapshotFile.absolutePath)

                Image(snapshotFile.absolutePath)

            } else {
                logger.debug("failed to restore shapshot for: {}", route.id)

                throw RuntimeException("failed to restore shapshot for route with id: ${route.id}")
            }
        }
    }

    private fun fileForRoute(route: Route): File {
        return File(routesDirectory, "route_${route.id}.png")
    }
}
