package com.f0ck.f0ckapp

import android.content.ContentValues
import android.content.Context
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.NonNull
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import java.io.File
import java.io.FileInputStream

class MainActivity : FlutterActivity() {
  private val CHANNEL = "MediaShit"

  override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine): Unit {
    super.configureFlutterEngine(flutterEngine)

    MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler {
            call,
            result ->
      if (call.method == "saveFile") {
        val filePath = call.argument<String>("filePath")
        val fileName = call.argument<String>("fileName")
        val subDir = call.argument<String?>("subDir")

        if (filePath == null || fileName == null)
                result.error("SAVE_FAILED", "file not found", null)

        if (!saveFileUsingMediaStore(applicationContext, filePath!!, fileName!!, subDir))
                result.error("COPY_FAILED", "Datei konnte nicht gespeichert werden", null)
        result.success(true)
      } else result.notImplemented()
    }
  }

  private fun saveFileUsingMediaStore(
          context: Context,
          filePath: String,
          fileName: String,
          subDir: String?
          
  ): Boolean {
    val srcFile = File(filePath)
    if (!srcFile.exists()) return false

    val values =
            ContentValues().apply {
              put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)
              put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS + "/" + (subDir ?: "f0ck"))
              put(MediaStore.MediaColumns.IS_PENDING, 1)
            }

    val resolver = context.contentResolver
    val collection = MediaStore.Downloads.EXTERNAL_CONTENT_URI
    val uri = resolver.insert(collection, values) ?: return false

    resolver.openOutputStream(uri).use { out ->
      FileInputStream(srcFile).use { input -> input.copyTo(out!!, 4096) }
    }

    values.clear()
    values.put(MediaStore.MediaColumns.IS_PENDING, 0)
    resolver.update(uri, values, null, null)

    return true
  }
}
