package ch.threema.app.files

import ch.threema.common.files.FileHandle
import ch.threema.localcrypto.MasterKeyProvider
import java.io.IOException
import java.io.OutputStream

class EncryptedFileHandle(
    private val masterKeyProvider: MasterKeyProvider,
    private val file: FileHandle,
) : FileHandle by file {
    @Throws(IOException::class)
    override fun read() =
        file.read()?.let { inputStream ->
            val masterKey = masterKeyProvider.getMasterKey()
            masterKey.decrypt(inputStream)
        }

    @Throws(IOException::class)
    override fun write(): OutputStream =
        masterKeyProvider.getMasterKey().encrypt(file.write())

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false
        other as EncryptedFileHandle
        if (masterKeyProvider != other.masterKeyProvider) return false
        if (file != other.file) return false
        return true
    }

    override fun hashCode(): Int {
        var result = masterKeyProvider.hashCode()
        result = 31 * result + file.hashCode()
        return result
    }

    override fun toString() = "Encrypted[$file]"
}
