package com.tt.honeyDue.platform

import androidx.compose.runtime.Composable
import androidx.compose.ui.interop.LocalUIViewController
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.models.HoneyDueShareCodec
import com.tt.honeyDue.models.Contractor
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.addressOf
import kotlinx.cinterop.usePinned
import platform.Foundation.*
import platform.UIKit.UIActivityViewController
import platform.UIKit.UIViewController

@Composable
actual fun rememberShareContractor(): (Contractor) -> Unit {
    val viewController = LocalUIViewController.current

    return share@{ contractor: Contractor ->
        val currentUsername = DataManager.currentUser.value?.username ?: "Unknown"
        val jsonContent = HoneyDueShareCodec.encodeContractorPackage(contractor, currentUsername)
        val fileUrl = writeShareFile(jsonContent, contractor.name) ?: return@share
        presentShareSheet(viewController, fileUrl)
    }
}

@OptIn(ExperimentalForeignApi::class)
private fun writeShareFile(jsonContent: String, displayName: String): NSURL? {
    val fileName = HoneyDueShareCodec.safeShareFileName(displayName)
    val filePath = NSTemporaryDirectory().plus(fileName)

    val bytes = jsonContent.encodeToByteArray()
    val data = bytes.usePinned { pinned ->
        NSData.create(bytes = pinned.addressOf(0), length = bytes.size.toULong())
    }
    val didCreate = NSFileManager.defaultManager.createFileAtPath(
        path = filePath,
        contents = data,
        attributes = null
    )
    if (!didCreate) return null

    return NSURL.fileURLWithPath(filePath)
}

private fun presentShareSheet(viewController: UIViewController, fileUrl: NSURL) {
    val activityViewController = UIActivityViewController(
        activityItems = listOf(fileUrl),
        applicationActivities = null
    )
    viewController.presentViewController(
        viewControllerToPresent = activityViewController,
        animated = true,
        completion = null
    )
}
