//
//  EnxStreamView.swift
//  Enx
//
//  Created by Daljeet Singh on 04/04/19.
//  Copyright © 2019 Facebook. All rights reserved.
//

import Foundation
import EnxRTCiOS
@objc(EnxStreamView)
class EnxStreamView : UIView {
    @objc var streamId: NSString?
    @objc var isLocal: NSString?
    @objc var isFrontCamera:Bool=true
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        if streamId != nil{
        let player = EnxRN.sharedState.players[(streamId)! as String]
        var stream = EnxRN.sharedState.subscriberStreams[(streamId)! as String]
        if stream == nil {
              stream = EnxRN.sharedState.publishStreams[(streamId)! as String]
        }
        if player != nil{
            player?.frame = self.bounds
            player?.removeFromSuperview()
           // player?.contentMode = UIView.ContentMode.scaleAspectFill
            if(stream != nil){
                if(stream!.enxPlayerView != nil){
                    stream!.detachRenderer()
                 
                }
                stream?.attachRenderer(player!)
            }
            self.addSubview(player!)
        }
            else {
                if(isLocal == "local"){
                    
                    let player = EnxPlayerView(withLocalView: self.bounds)
                    //EnxPlayerView.init(localView: self.bounds)
                    //  player?.contentMode = UIView.ContentMode.scaleAspectFill
                    EnxRN.sharedState.players.updateValue(player, forKey: streamId! as String)
                    if(stream != nil){
                        if(stream!.enxPlayerView != nil){
                            stream!.detachRenderer()
                            
                         }
                        stream?.attachRenderer(player)
                    }
                    self.addSubview(player)
                }
                else {
                    let player =  EnxPlayerView(withRemoteView: self.bounds)
                    //EnxPlayerView.init(remoteView: self.bounds)
                    
                    // player?.contentMode = UIView.ContentMode.scaleAspectFill
                    EnxRN.sharedState.players.updateValue(player, forKey: streamId! as String)
                    if(stream != nil){
                        if(stream!.enxPlayerView != nil){
                            stream!.detachRenderer()
                           
                         }
                        stream?.attachRenderer(player)
                    }
                    self.addSubview(player)
                }
            }
      }
     }
    }


