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

import Foundation

class OpenTokLocalVideoFactory: NSObject, FlutterPlatformViewFactory {
    static var view: LocalVideoPlatformView?
    
    static var viewToAddPub: UIView?
    
    static func getViewInstance(
        frame: CGRect,
        viewId: Int64,
        args: Any?,
        messenger: FlutterBinaryMessenger?
    ) -> LocalVideoPlatformView{
        if(view == nil) {
            view = LocalVideoPlatformView()
            if viewToAddPub != nil {
                view?.addPublisherView(viewToAddPub!)
            }
        }
        
        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 OpenTokLocalVideoFactory.getViewInstance(
            frame: frame,
            viewId: viewId,
            args: args,
            messenger: messenger)
    }
}

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

final class LocalVideoContainer: UIView {
    private let publisherContainer = UIView()
    
    init() {
        super.init(frame: .zero)
        addSubview(publisherContainer)
    }
    
    public func addPublisherView(_ view: UIView) {
        publisherContainer.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
        
        publisherContainer.frame = CGRect(x: 0, y: 0, width: width, height: height)
    }
}
