/*
 * This file is part of the Scandit Data Capture SDK
 *
 * Copyright (C) 2022- Scandit AG. All rights reserved.
 */

import React
import ScanditBarcodeCapture
import ScanditDataCaptureCore
import ScanditFrameworksCore

class RNTSparkScanViewWrapper: UIView {
    var isFrameSet = false

    var sparkScanView: SparkScanView? {
        subviews.first { $0 is SparkScanView } as? SparkScanView
    }

    var postFrameSetAction: (() -> Void)?

    weak var viewManager: SparkScanViewManager?

    override func didMoveToWindow() {
        super.didMoveToWindow()
        // Drives the JS single-owner camera model (SDC-32484): attach -> the
        // hosting wrapper claims camera ownership, detach -> it releases.
        ViewWindowEventsRelay.notifyWindowChanged(viewId: reactTag.intValue, attached: window != nil)
    }

    override func removeFromSuperview() {
        super.removeFromSuperview()
        guard let index = SparkScanViewManager.containers.firstIndex(of: self) else {
            return
        }

        SparkScanViewManager.containers.remove(at: index)

        if let viewManager = viewManager {
            _ = viewManager.getAndRemovePostContainerCreateAction(for: self.reactTag.intValue)
        }
    }

    override func didMoveToSuperview() {
        // Was added to the super view, if no sparkScanView yet
        if let viewManager = viewManager {
            let postCreationAction = viewManager.getAndRemovePostContainerCreateAction(for: self.reactTag.intValue)
            postCreationAction?(self)
        }
    }

    override func layoutSubviews() {
        super.layoutSubviews()
        // This is needed only the first time to execute the action queued in the postFrameSetAction
        if !frame.equalTo(.zero) && !isFrameSet {
            isFrameSet = true
            postFrameSetAction?()
        }
    }

    override func didUpdateReactSubviews() {
        super.didUpdateReactSubviews()
        // Ensure SparkScanView is always on top
        if let sparkScanView = subviews.first(where: { $0 is SparkScanView }) {
            bringSubviewToFront(sparkScanView)
        }
    }
}

@objc(RNTSDCSparkScanViewManager)
class SparkScanViewManager: RCTViewManager {
    static var containers: [RNTSparkScanViewWrapper] = []

    override class func requiresMainQueueSetup() -> Bool {
        true
    }

    private var postContainerCreateActions: [Int: ((RNTSparkScanViewWrapper) -> Void)] = [:]

    public func setPostContainerCreateAction(for viewId: Int, action: @escaping (RNTSparkScanViewWrapper) -> Void) {
        postContainerCreateActions[viewId] = action
    }

    func getAndRemovePostContainerCreateAction(for viewId: Int) -> ((RNTSparkScanViewWrapper) -> Void)? {
        let action = postContainerCreateActions[viewId]
        postContainerCreateActions.removeValue(forKey: viewId)
        return action
    }

    override func view() -> UIView! {
        let container = RNTSparkScanViewWrapper()
        container.viewManager = self
        SparkScanViewManager.containers.append(container)

        return container
    }
}
