/*
 * Eazytec is pleased to support the open source community by making Skiko available.
 * Copyright (C) 2026 Eazytec. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

@file:OptIn(kotlinx.cinterop.ExperimentalForeignApi::class)

package org.jetbrains.skia

import org.jetbrains.skia.ExternalSymbolName
import org.jetbrains.skia.impl.NativePointer
import org.jetbrains.skia.impl.Native
import org.jetbrains.skia.impl.Stats
import org.jetbrains.skia.impl.getPtr
import org.jetbrains.skia.impl.reachabilityBarrier

/**
 * Import an OH_NativeBuffer-backed texture into Skia.
 *
 * For YUV420 SP buffers (`YCRCB_420_SP` / `YCBCR_420_SP`), native code detects format and
 * forces opaque RGBA8 semantics on the **sampled** result (GPU converts YUV→RGB). Caller
 * [colorType]/[alphaType] are ignored in that case.
 */
@Deprecated(
    message = "Use a renderer-scoped OhosImageInteropSession instead",
)
fun Image.Companion.makeFromOhosSurfaceBuffer(
    context: DirectContext,
    surfaceBufferPtr: NativePointer,
    colorType: ColorType = ColorType.RGBA_8888,
    alphaType: ColorAlphaType = ColorAlphaType.PREMUL,
    colorSpace: ColorSpace = ColorSpace.sRGB
): Image {
    return try {
        Stats.onNativeCall()
        val ptr = _nMakeFromOhosSurfaceBuffer(
            getPtr(context),
            surfaceBufferPtr,
            colorType.ordinal,
            alphaType.ordinal,
            getPtr(colorSpace)
        )
        if (ptr == Native.NullPointer) throw RuntimeException("Failed to makeFromOhosSurfaceBuffer")
        Image(ptr)
    } finally {
        reachabilityBarrier(context)
        reachabilityBarrier(colorSpace)
    }
}

fun drainOhosSurfaceBufferReleases() {
    Stats.onNativeCall()
    _nDrainOhosSurfaceBufferReleases()
}

@ExternalSymbolName("org_jetbrains_skia_Image__1nMakeFromOhosSurfaceBuffer")
private external fun _nMakeFromOhosSurfaceBuffer(
    contextPtr: NativePointer,
    surfaceBufferPtr: NativePointer,
    colorType: Int,
    alphaType: Int,
    colorSpacePtr: NativePointer
): NativePointer

@ExternalSymbolName("org_jetbrains_skia_Image__1nDrainOhosSurfaceBufferReleases")
private external fun _nDrainOhosSurfaceBufferReleases()
