Metuuu
2/7/2018 - 2:12 PM

TemporaryImageManager

import android.content.Context
import android.graphics.Bitmap
import android.net.Uri
import java.io.File
import java.io.FileOutputStream

/**
 * Created by lauri on 07/02/2018.
 */

object TemporaryImageManager {

	private const val SHARED_PREF_TEMP_FILES = "tmp_files"
	private const val KEY_TMP_IMAGES = "tmp_images"

	private val temporaryImages: HashMap<String, Uri> = hashMapOf()

	fun newImage(id: String?, bitmap: Bitmap, context: Context): Uri {
		val file = File.createTempFile("img", null, context.cacheDir)
		val stream = FileOutputStream(file)
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream)
		stream.flush()
		stream.close()
		val uri = Uri.fromFile(file)
		addTempImage(uri, context)
		if (id != null) temporaryImages[id] = uri
		return uri
	}

	fun getTemporaryImage(id: String): Uri? {
		return temporaryImages[id]
	}


	fun deleteTemporaryImages(context: Context) {
		val images = getTempImages(context)
		if (images.isNotEmpty()) {
			context.getSharedPreferences(SHARED_PREF_TEMP_FILES, Context.MODE_PRIVATE).edit().clear().apply()
			images.forEach {
				val uri = Uri.parse(it)
				var id: String? = null
				run breaker@ {
					temporaryImages.forEach {
						if (uri.path == it.value.path) {
							id = it.key
							return@breaker
						}
					}
				}
				if (!File(uri.path).delete()) {
					addTempImage(uri, context)
				} else {
					if (id != null) temporaryImages.remove(id!!)
				}
			}
		}
	}

	private fun addTempImage(uri: Uri, context: Context) {
		val images = getTempImages(context).toHashSet()
		val sharedPreferences = context.getSharedPreferences(SHARED_PREF_TEMP_FILES, Context.MODE_PRIVATE)
		val editor = sharedPreferences.edit()
		images.add(uri.path)
		editor.putStringSet(KEY_TMP_IMAGES, images).apply()
	}

	private fun getTempImages(context: Context): Set<String> {
		val sharedPreferences = context.getSharedPreferences(SHARED_PREF_TEMP_FILES, Context.MODE_PRIVATE)
		return sharedPreferences.getStringSet(KEY_TMP_IMAGES, setOf())
	}
	
}