//
//  OpenTokRemoteVideoFactory.swift
//  Runner
//
//  Created by Zohaib Iqbal Kambrani on 20/10/2021.
//

import Foundation

class OpenTokRemoteVideoFactory: NSObject, FlutterPlatformViewFactory {
    static var view: RemoteVideoPlatformView?
    
    static var viewToAddSub: UIView?
    
    static func getViewInstance(
        frame: CGRect,
        viewId: Int64,
        args: Any?,
        messenger: FlutterBinaryMessenger?
    ) -> RemoteVideoPlatformView{
        if(view == nil) {
            view = RemoteVideoPlatformView()
            if viewToAddSub != nil {
                view?.addSubscriberView(viewToAddSub!)
            }
        }
        
        return view!
    }
    
    private var messenger: FlutterBinaryMessenger
    
    init(messenger: FlutterBinaryMessenger) {
        self.messenger = messenger
        super.init()
    }
    
    func create(
        withFrame frame: CGRect,
        viewIdentifier viewId: Int64,
        arguments args: Any?
    ) -> FlutterPlatformView {
        return OpenTokRemoteVideoFactory.getViewInstance(
            frame: frame,
            viewId: viewId,
            args: args,
            messenger: messenger)
    }
}

class RemoteVideoPlatformView: NSObject, FlutterPlatformView {
    private let videoContainer: RemoteVideoContainer
    
    override init() {
        videoContainer = RemoteVideoContainer()
        super.init()
    }
    
    public func addSubscriberView(_ view: UIView) {
        videoContainer.addSubscriberView(view)
    }
    
    func view() -> UIView {
        return videoContainer
    }
}

final class RemoteVideoContainer: UIView {
    private let subscriberContainer = UIView()
    
    init() {
        super.init(frame: .zero)
        addSubview(subscriberContainer)
    }
    
    
    public func addSubscriberView(_ view: UIView) {
        subscriberContainer.addSubview(view)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let width = frame.width
        let height = frame.height
        subscriberContainer.frame = CGRect(x: 0, y: 0, width: width, height: height)
    }
}
