package xyz.myachin.saveto.logic.file

import android.content.ContentResolver
import android.content.Intent
import android.net.Uri
import android.util.Log
import xyz.myachin.saveto.logic.FP
import xyz.myachin.saveto.logic.intent.ContentType
import xyz.myachin.saveto.logic.intent.IntentProcessor
import java.io.InputStream
import java.io.OutputStream

class FileProcessor(private val intentProcessor: IntentProcessor) {
    private var mInputSteam: InputStream? = null
    private var mOutputSteam: OutputStream? = null
    private lateinit var mCr: ContentResolver

    fun prepareOutput(data: Uri?, contentResolver: ContentResolver): Boolean {
        if (data == null) return false
        mCr = contentResolver
        mOutputSteam = mCr.openOutputStream(data)
        mOutputSteam?.run {
            return true
        }
        return false
    }

    fun getRemoveFileIntent(): Intent? {
        return intentProcessor.mRemoveIntent
    }

    private fun writeTextFile() {
        mOutputSteam?.write(intentProcessor.extraText.encodeToByteArray())
        closeStreams()
    }

    private fun writeBinFile() {
        mCr.openInputStream(intentProcessor.streamDataUri!!)?.copyTo(mOutputSteam!!)
        closeStreams()
    }

    fun closeStreams() {
        mInputSteam?.close()
        mOutputSteam?.close()
    }

    fun writeFile() {
        when (intentProcessor.mContentType) {
            ContentType.FILE -> writeBinFile()
            ContentType.TEXT -> writeTextFile()
            else -> {
                Log.wtf(FP, "writeFile: unexpected content type: ${intentProcessor.mContentType}")
                closeStreams()
            }
        }
    }
}