package xyz.myachin.saveto.logic.file

import android.content.ContentResolver
import android.content.Intent
import android.util.Log
import android.widget.Toast
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 mIp: IntentProcessor) {
    private var mInputSteam: InputStream? = null
    private var mOutputSteam: OutputStream? = null
    private lateinit var mCr: ContentResolver

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

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

    private fun writeTextFile() {
        mOutputSteam?.write(mIp.mText.encodeToByteArray())
        closeStreams()
    }

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

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

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