import UIKit
import AVKit
import BrightcovePlayerSDK

@available(iOS 12.0, *)
public class BrightcoveVideoPlayerViewController: UIViewController {

    var watermarkText = UILabel();
    var screen : UIView? = nil;
    var completedFired = false;
    let setup : BrightcoveSetup
    let startAt: Int? = nil
    var playbackController :BCOVPlaybackController?
    var videoId : String? = nil
    var animatedText : String? = nil
    var local: Bool? = nil
    var token: String? = nil
    var subtitle: String? = nil
    var nowPlayingHandler: BrightcoveVideoPlayerNowPlayingHandler?
    
    var currentProgress: TimeInterval?
    var currentSession: BCOVPlaybackSession?
    var duration: Double?
    var playerView: BCOVPUIPlayerView?
    let closeButton = UIButton(type: .custom);
    var questionText = UILabel()
    var questionHint = UILabel()
    var questionsList = Array<PopUpQuestionsModel>()
    var questionTimeInSec = [Int]()
    var questionsTimer = Timer();
    var currentQuestion : Int = 0;
    var isQuestionShown : Bool = false;
    var selectedAnswerIndex : Int?;
    var multipleSelectedAnswerIndex = [Int]();
    var bgView = UIView()
    var questionBG = UIView()
    var appLanguage: String? = "en"
    var closeVideoCalled = false
    var readyToUpdateSubtitle = false

    var currentProgressMillis: Int = 0

    var startPosition: Int = 0

    static var shared = DownloadService()

    required init?(coder: NSCoder) {
        fatalError(PluginError.NOT_IMPLEMENTED.rawValue)
    }

    init(setup: BrightcoveSetup, startPosition: Int, videoId: String?, local: Bool?, subtitle: String?,animatedText: String?) throws {
        self.currentProgress = 0
        self.setup = setup
        self.videoId = videoId
        self.local = local
        self.startPosition = startPosition
        self.subtitle = subtitle
        self.token = nil
        self.animatedText = animatedText

        super.init(nibName: nil, bundle: nil)

        try self.checkVideoId()

        self.playbackController = (setup.sharedSDKManager.createPlaybackController())!

        if(super.modalPresentationStyle != .fullScreen) {
            super.modalPresentationStyle = .fullScreen
        }

        playbackController!.delegate = self
        playbackController!.isAutoAdvance = true
        playbackController!.isAutoPlay = true
        playbackController!.allowsBackgroundAudioPlayback = true
        playbackController!.allowsExternalPlayback = true
    }

    public override func viewDidLoad() {
        super.viewDidLoad()

        let value = UIInterfaceOrientation.landscapeLeft.rawValue
                UIDevice.current.setValue(value, forKey: "orientation")
        NotificationCenter.default.addObserver(self, selector: #selector(self.preventScreenRecording(notification:)), name: UIScreen.capturedDidChangeNotification, object: nil)
        
        let gesture = UISwipeGestureRecognizer(target: self, action: #selector(gestureDismiss))
                gesture.direction = .down
                view.isUserInteractionEnabled = true
                view.addGestureRecognizer(gesture)
        
        let options = BCOVPUIPlayerViewOptions()
        options.showPictureInPictureButton = false
            
        
        let sdkManager = BCOVPlayerSDKManager.sharedManager()
        bgView = UIView(frame: UIScreen.main.bounds)
    

        // Set up our player view. Create with a standard VOD layout.
        guard let playerView = BCOVPUIPlayerView(playbackController: self.playbackController, options: options, controlsView: BCOVPUIBasicControlView.withVODLayout()) else {
            return
        }

        self.playerView = playerView

        // Install in the container view and match its size.
        view.addSubview(playerView)
        playerView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            playerView.topAnchor.constraint(equalTo: view.topAnchor),
            playerView.rightAnchor.constraint(equalTo: view.rightAnchor),
            playerView.leftAnchor.constraint(equalTo: view.leftAnchor),
            playerView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        playerView.delegate = self
        playerView.playbackController = playbackController

        self.closeButton.addTarget(self, action: #selector(closeVideo), for: .touchUpInside)
        self.closeButton.setTitle("❌", for: .normal)
        self.closeButton.setTitleColor(UIColor.white, for: .normal)
        self.closeButton.translatesAutoresizingMaskIntoConstraints = false
        playerView.controlsFadingView.addSubview(self.closeButton)

        //water mark
//        watermarkStyle()
//        playerView.controlsStaticView.addSubview(self.watermarkText)


        self.playerView = playerView
        self.playerView?.performScreenTransition(with: BCOVPUIScreenMode.full)

        self.closeButton.rightAnchor.constraint(equalTo: (self.playerView?.safeAreaLayoutGuide.rightAnchor)!).isActive = true
//        self.watermarkText.leftAnchor.constraint(equalTo: (self.playerView?.safeAreaLayoutGuide.leftAnchor)!).isActive = true
//
//        let updateTimer = Timer.scheduledTimer(timeInterval: 10, target: self, selector:#selector(self.startAnimate), userInfo: nil, repeats: true)
//
//        updateTimer.fire()
        print("Brightcove plugin: BrightCoveVideoPlayerViewController::viewDidLoad");

        retrieveQuestions()
    }
    public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
                return .landscape
            }

        public override var shouldAutorotate: Bool {
            return true
        }
    @objc func watermarkStyle() {
        
        
        if let font =  UIFont(name: "Verdana", size: 18) {
            
            let textFontAttributes = [
                NSAttributedString.Key.font : font,
                // Note: SKColor.whiteColor().CGColor breaks this
                NSAttributedString.Key.foregroundColor: UIColor.gray,
                NSAttributedString.Key.strokeColor: UIColor.black,
                // Note: Use negative value here if you want foreground color to show
                NSAttributedString.Key.strokeWidth: -3
            ] as [NSAttributedString.Key : Any]
            
            let myMutableString = NSMutableAttributedString(string: self.animatedText ?? "", attributes: textFontAttributes)
                    
            self.watermarkText =  UILabel(frame: CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width: 200, height: 21)))
            self.watermarkText.attributedText = myMutableString
            self.watermarkText.center = CGPoint(x: 160, y: 285)
            self.watermarkText.translatesAutoresizingMaskIntoConstraints = false
        }
        
        
    }

    @objc func startAnimate() {
        
        self.animateView(viewToAnimate: self.watermarkText)
    }

    @objc
    private func animateView(viewToAnimate:UIView) {
        

        let randomWidthFloat1   = CGFloat.random(in: 0..<(UIScreen.main.bounds.width))
        
        let randomWidthFloat2   = CGFloat.random(in: 0..<(UIScreen.main.bounds.width))
        let randomHeightFloat1   = CGFloat.random(in: 0..<(UIScreen.main.bounds.height))
        
        let randomHeightFloat2  = CGFloat.random(in: 0..<(UIScreen.main.bounds.height))
        
        UIView.animateKeyframes(withDuration: 10, //1
          delay: 0, //2
          options: .calculationModeLinear, //3
          animations: { //4
            UIView.addKeyframe( //5
             withRelativeStartTime: 0, //6
              relativeDuration: 0.5) { //7
                  viewToAnimate.center = CGPoint(x: randomWidthFloat1, y: randomHeightFloat1) //8
            }

            UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {
                viewToAnimate.center = CGPoint(x:randomWidthFloat2, y:randomHeightFloat2)
            }

    
            
        })
    }
    
    
    @objc
    private func gestureDismiss() {
        self.playbackController!.pause()
        self.closeVideo()
    }
    
    @objc
    private func text() {
    }
    
    @objc func preventScreenRecording(notification: NSNotification) {
         var isCaptured  = false
        for screen in UIScreen.screens {
            if(screen.isCaptured || (screen.mirrored != nil))
            {
                isCaptured = true
            }
        }
        print("from bright took screen",isCaptured);
        if (isCaptured) {
                self.view?.alpha = 0;
                self.view?.isHidden = true;
            }
            else {
                self.view?.alpha = 1;
                self.view?.isHidden = false;
            }
      
    }

    public func pauseVideo() throws {
        if let playbackController = self.playbackController {
            playbackController.pause()
        }
    }

    public func resumeVideo() throws {
        if let playbackController = self.playbackController {
            playbackController.play()
        }
    }

    @objc
    public func closeVideo() {
        self.closeVideoCalled = true
        self.readyToUpdateSubtitle = false
        self.playbackController!.pause()
        self.currentSession?.player.replaceCurrentItem(with: nil)

        NotificationCenter.default.post(name: Notification.Name("beforeVideoClose"), object: nil)
        let callback = {() -> Void in
            let duration = self.duration != nil ? (Double(self.duration!) * 1000):0;
            var position = Double(self.currentProgressMillis);
            let completedVl = position >= (Double(duration) - 5000) || self.completedFired;
            
            if(self.completedFired)
            {
                position = Double(duration)
            }
            NotificationCenter.default.post(
                name: Notification.Name("videoClosed"), object: nil,
                userInfo: [
                    "completed": completedVl,
                    "currentMillis": position,
                    "totalMillis": Int(self.duration!) * 1000,
                    "subtitle": self.subtitle ?? ""
                ]
            )
        }
        self.dismiss(animated: false, completion: callback);
    }

    func requestContentFromPlaybackService() throws {
        self.local = self.local == nil ? false : self.local
        self.local! ? try self.loadLocalVideo() : try self.loadOnlineVideo()
    }

    private func loadLocalVideo() throws {
        for offlineVideoStatus in BCOVOfflineVideoManager.shared()!.offlineVideoStatus() {
            let token = offlineVideoStatus.offlineVideoToken!;
            let downloadedVideoId = BCOVOfflineVideoManager.shared()?.videoObject(fromOfflineVideoToken: token)!.properties[kBCOVVideoPropertyKeyId]!
            if (downloadedVideoId! as! String == self.videoId!) {
                self.token = token;
            }
        }

        guard self.token != nil || NetworkService.isConnected! else {
            throw CustomError(PluginError.FILE_NOT_EXIST_AND_NO_INTERNET,
                              "BrightcoveVideoPlayerViewController.loadLocalVideo: The plugin needs an internet connection or the media to be downloaded to access the metadata (token: \(String(describing: self.token)), mediaId: \(String(describing: self.videoId!))")
        }
        
        if(self.token == nil) {
            print("Brightcove plugin: No local media, stream online media")
            return try self.loadOnlineVideo()
        }
        
        // Check that the status of the download is completed. If not, we load the remote media
        if let downloadStatus = BCOVOfflineVideoManager.shared()?.offlineVideoStatus(forToken: self.token) {
            if downloadStatus.downloadState != .stateCompleted {
                print("Brightcove plugin: Local media is not available yet status: \(String(describing: downloadStatus.downloadState))")
                return try self.loadOnlineVideo()
            }
        }
        
        print("Brightcove plugin: Run local video with token \(self.token!)")
        let video = BCOVOfflineVideoManager.shared()?.videoObject(fromOfflineVideoToken: self.token)
        if let v = video {
            self.setVideoProperties(video: v)
            self.playbackController!.setVideos([v] as NSArray)
        }
    }

    private func setVideoProperties(video: BCOVVideo) {
        self.duration = (video.properties["duration"]! as! Double) / 1000
    }

    private func loadOnlineVideo() throws {
        try NetworkService.checkIfOnline()

        setup.playbackService.findVideo(withVideoID: self.videoId!, parameters: nil) { (video: BCOVVideo?, jsonResponse: [AnyHashable: Any]?, error: Error?) -> Void in
           if let v = video {
               self.setVideoProperties(video: v)
               self.playbackController!.setVideos([v] as NSArray)
           } else {
               print("Brightcove plugin: ViewController Debug - Error retrieving video: \(error?.localizedDescription ?? "unknown error")")
           }
        }
    }


    private func checkVideoId() throws {
        if(self.videoId == nil || self.videoId! == "") {
            throw PluginError.MISSING_FILEID
        }
    }

    public func forward(millis: Float64) {
        self.seekRelative(millis: millis)
    }

    public func backward(millis: Float64) {
        self.seekRelative(millis: -millis)
    }

    public func seekRelative(millis: Float64) {
        guard let position = currentProgress else {
            return
        }

        var newTime = position + millis/1000
        if newTime < 0 {
            newTime = 0
        }

        if(newTime < self.duration!) {
            let resultingTime: CMTime = CMTimeMake(value: Int64(newTime * 1000 as Float64), timescale: 1000)
            self.playbackController!.seek(to: resultingTime, completionHandler: nil)

            self.currentProgressMillis = Int(newTime * 1000)
            videoPositionChangeEvent()
        }
    }

    public func setupNowPlayingHandler() {
        if(nowPlayingHandler != nil) {
            return
        }

        self.nowPlayingHandler = BrightcoveVideoPlayerNowPlayingHandler(withPlaybackController: self.playbackController!, session: self.currentSession!)
        self.nowPlayingHandler!.playAction = {() -> Void in
            self.playbackController?.play()
        }
        self.nowPlayingHandler!.pauseAction = {() -> Void in
            self.playbackController?.pause()
        }
        self.nowPlayingHandler!.skipForwardAction = {() -> Void in
            self.forward(millis: Float64(self.nowPlayingHandler!.skipForwardIntervalSeconds * 1000))
        }
        self.nowPlayingHandler!.skipBackwardAction = {() -> Void in
            self.backward(millis: Float64(self.nowPlayingHandler!.skipBackwardIntervalSeconds * 1000))
        }
        self.nowPlayingHandler!.changePlaybackPositionAction = {(event) -> Void in
            let time = CMTime(seconds: event.positionTime, preferredTimescale: 1000000)
            self.playbackController?.seek(to: time, completionHandler: nil)
        }
    }

    private func retrieveQuestions(){
        
//        let userDefaults =  UserDefaults(suiteName: "com.appenza.VOD_NativeStorage")
//        let testUser = userDefaults!.dictionaryRepresentation()
//
//
//        print("TestUserDefaults  \(UserDefaults.standard.dictionaryRepresentation())")
//        print(" Home Test Dir \(NSHomeDirectory())")
        let prefrences = UserDefaults.standard;
        
        let questions = prefrences.string(forKey: videoId!)
        appLanguage = prefrences.string(forKey: "appLanguage")
        if let range = appLanguage!.range(of: "(?<=\\\").*?(?=\\\")", options: .regularExpression) {
            appLanguage = appLanguage!.substring(with: range)
        }
//        print("Heeeeeeey \(prefrences.dictionaryRepresentation().keys)")

        let decoder = JSONDecoder()
        do {
            let data =  Data(questions!.utf8 )
            questionsList = try decoder.decode(Array<PopUpQuestionsModel>.self, from: data)
            if(questionsList.count != 0){
                
                questionsList.forEach { item in
                    if let minutes = item.minutes, let seconds = item.seconds {
                        questionTimeInSec.append(minutes * 60 + seconds)
                    }
                }
            
                questionsTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(self.initQuestionsTimers), userInfo: nil, repeats: true)

                questionsTimer.fire()
//                try requestContentFromPlaybackService()
                //addCuePoint()
                showQuestionHint()
            }
            print("Heeey \(questionsList)")
        } catch {
            print("Question Model  \(error)")
        }
        
    }
    
    private func saveAnswerData(){
        let prefrences = UserDefaults.standard;
        let encoder = JSONEncoder()
        do{
           if(selectedAnswerIndex != nil)
            { let studentAnswer =  try encoder.encode(questionsList[currentQuestion].questionBankAnswers[selectedAnswerIndex!])
            prefrences.set( studentAnswer, forKey: "studentPopUpAnswers")
           }
        }
        catch{
            
        }
    }
    
    @objc private func initQuestionsTimers(){
        
        for (index,item) in  questionTimeInSec.enumerated() {
            if(item == currentProgressMillis / 1000)
            {
                currentQuestion = index
                setPopUpQuestions()
            }
        }
       
    }
    
    private func showQuestionHint(){
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: "question_hint")
        let attachmentString = NSMutableAttributedString(attachment: attachment)

        if let font =  UIFont(name: "Verdana", size: 16) {

            let textFontAttributes = [
                NSAttributedString.Key.font : font,
                NSAttributedString.Key.foregroundColor: hexStringToUIColor(hex: "#FFC048"),
//                NSAttributedString.Key.strokeColor: hexStringToUIColor(hex: "#FFC048"),
                // Note: Use negative value here if you want foreground color to show
//                NSAttributedString.Key.strokeWidth: 1
            ] as [NSAttributedString.Key : Any]
            
            let myMutableString = NSMutableAttributedString(string: appLanguage == "ar" ? "   هذا الدرس يحتوى على أسئلة تفاعلية    " : "This lesson contains interactive questions", attributes: textFontAttributes)
            let sizeSide: CGFloat = 16
            let iconsSize = CGRect(x: CGFloat(0),
                                   y: (font.capHeight - sizeSide) / 2,
                                   width: sizeSide,
                                   height: sizeSide)
            attachment.bounds = iconsSize
            attachmentString.append(NSAttributedString(string: " "))
            attachmentString.append(myMutableString)

            self.questionHint =  UILabel(frame: CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width: 200, height: 21)))
            self.questionHint.attributedText = attachmentString
            self.questionHint.center = CGPoint(x: 160, y: 285)
            self.questionHint.translatesAutoresizingMaskIntoConstraints = false

        }

        playerView?.controlsStaticView.addSubview(self.questionHint)
       self.questionHint.rightAnchor.constraint(equalTo: (self.playerView?.safeAreaLayoutGuide.rightAnchor)!).isActive = true
       self.questionHint.topAnchor.constraint(equalTo: (self.playerView?.safeAreaLayoutGuide.topAnchor)!,constant: 40).isActive = true
        
        let initialDelayInSeconds = 4
        let now = Date()
        let calendar = Calendar.current
        let date = calendar.date(bySettingHour: Calendar.current.component(.hour, from: now), minute: Calendar.current.component(.minute, from: now), second: Calendar.current.component(.second, from: now) + initialDelayInSeconds, of: now)!

        let questionHintTimer = Timer(fireAt: date,interval: 4, target: self, selector:#selector(self.hideQuestionHint), userInfo: nil, repeats: false)

        RunLoop.main.add(questionHintTimer, forMode: .common)
    }
    
    @objc private func hideQuestionHint(){
        questionHint.removeFromSuperview()
    }

    
    @objc private func setPopUpQuestions(){
        
        if(!questionsList.isEmpty){

            questionsTimer.invalidate()
            isQuestionShown = true
            showHideVideoControllers()
            bgView.frame = (playerView?.controlsStaticView!.bounds)!
            bgView.backgroundColor = UIColor(white: 0, alpha: 0.8)
            bgView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
//            let questionBG = UIView(frame: UIScreen.main.bounds)
            questionBG = UIView(frame: UIScreen.main.bounds.insetBy(dx: UIScreen.main.bounds.height / 5.5, dy: 35))
            questionBG.layer.cornerRadius = questionBG.frame.height / 12

//            questionBG.bounds = view.frame.insetBy(dx: 10.0, dy: 10.0)
//            questionBG.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 200, leading: 200, bottom: 200, trailing: 200)
            
            questionBG.backgroundColor = UIColor(hexString: "#FFFFE1")
            bgView.addSubview(questionBG)

            playerView?.controlsStaticView.addSubview(bgView)
      
            setQuestionTitle()
            if(questionsList[currentQuestion].questionBankType == .MultipleCorrectAnswer)
            {
                fillCheckButtonList(answersChecked: false)
            }
            else{
                fillRadioButtonList(answersChecked: false)
            }

        }
        
    }
    
    private func showHideVideoControllers(){
        
        isQuestionShown ? playbackController?.pause() : playbackController?.play()
        playbackController?.thumbnailSeekingEnabled = !isQuestionShown
        playerView?.isUserInteractionEnabled = !isQuestionShown
        playbackController?.view.isUserInteractionEnabled = !isQuestionShown
//        closeButton.isUserInteractionEnabled = !isQuestionShown
        playerView?.isHidden = isQuestionShown
        playerView?.delegate = isQuestionShown ? nil : self
        playerView?.playbackController =  isQuestionShown ? nil : playbackController
    }
    
   private func setQuestionTitle(){
        
       
       if let font =  UIFont(name: "Verdana", size: 18) {

           let textFontAttributes = [
               NSAttributedString.Key.font : font,
               // Note: SKColor.whiteColor().CGColor breaks this
               NSAttributedString.Key.foregroundColor: UIColor.black,
               NSAttributedString.Key.strokeColor: UIColor.black,
               // Note: Use negative value here if you want foreground color to show
               NSAttributedString.Key.strokeWidth: -3
           ] as [NSAttributedString.Key : Any]

           let myMutableString = NSMutableAttributedString(string: questionsList[currentQuestion].questionBankBody ?? "", attributes: textFontAttributes)

           self.questionText =  customRectLabel(withInsets: 5, 5, 10, 10)
           self.questionText.attributedText = myMutableString
           self.questionText.center = CGPoint(x: 160, y: 285)
           self.questionText.translatesAutoresizingMaskIntoConstraints = false
//           self.questionText.padding = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)
       }
       questionBG.addSubview(self.questionText)
       self.questionText.rightAnchor.constraint(equalTo: (self.questionBG.rightAnchor),constant: -25).isActive = true
       self.questionText.topAnchor.constraint(equalTo: (self.questionBG.topAnchor),constant: 20).isActive = true
   
    }
    
    
    private func knewAnswer(answerResult : Bool){
  
        var knewCorrectAnswer = UILabel()
        var correctedAnswer = UILabel()
        let attachment = NSTextAttachment()
        attachment.image = UIImage(named: answerResult ? "correct" : "wrong" )
        let attachmentString = NSMutableAttributedString(attachment: attachment)
        
        
        
        
        if let font =  UIFont(name: "Verdana", size: 16) {

            let textFontAttributes = [
                NSAttributedString.Key.font : font,
                // Note: SKColor.whiteColor().CGColor breaks this
                NSAttributedString.Key.foregroundColor: answerResult  ? UIColor.systemGreen : UIColor.systemRed,
                NSAttributedString.Key.strokeColor: answerResult  ? UIColor.systemGreen : UIColor.systemRed,
                // Note: Use negative value here if you want foreground color to show
                NSAttributedString.Key.strokeWidth: 0
            ] as [NSAttributedString.Key : Any]

            let myMutableString : NSMutableAttributedString
            if(appLanguage == "ar")
                {
                    myMutableString = NSMutableAttributedString(string: answerResult ? " اجابه صحيحة " :" اجابه خاطئة " , attributes: textFontAttributes)
                }
            else
                {
                myMutableString = NSMutableAttributedString(string: answerResult ? "Correct Answer" : "Wrong Answer" , attributes: textFontAttributes)
                }
        
            let sizeSide: CGFloat = 16
            let iconsSize = CGRect(x: CGFloat(0),
                                   y: (font.capHeight - sizeSide) / 2,
                                   width: sizeSide,
                                   height: sizeSide)
            attachment.bounds = iconsSize
            attachmentString.append(NSAttributedString(string: " "))
            attachmentString.append(myMutableString)

            correctedAnswer =  UILabel(frame: CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width: 100, height: 21)))
            correctedAnswer.attributedText = attachmentString
//            correctedAnswer.center = CGPoint(x: 0, y: 0)
            correctedAnswer.translatesAutoresizingMaskIntoConstraints = false
        }
        
        questionBG.addSubview(correctedAnswer)
        correctedAnswer.rightAnchor.constraint(equalTo: (self.questionBG.rightAnchor),constant: -10).isActive = true
        correctedAnswer.bottomAnchor.constraint(equalTo: (self.questionBG.bottomAnchor),constant: -40).isActive = true
        
        
        if let font =  UIFont(name: "Verdana", size: 16) {

            let textFontAttributes = [
                NSAttributedString.Key.font : font,
                NSAttributedString.Key.foregroundColor: UIColor.black,
//                NSAttributedString.Key.strokeColor: UIColor.black,
            ] as [NSAttributedString.Key : Any]

            let myMutableString : NSMutableAttributedString
            if(appLanguage == "ar")
            {
                myMutableString = NSMutableAttributedString(string: answerResult ? "استمرار" :"تعلمت الاجابه الصحيحة"  , attributes: textFontAttributes)
            }
            else
            {
                myMutableString = NSMutableAttributedString(string: answerResult ?  "Continue" : "Learned the correct answer" , attributes: textFontAttributes)
            }

            knewCorrectAnswer =  customRectLabel(withInsets: 5,5,10,10);
            knewCorrectAnswer.attributedText = myMutableString
//            knewCorrectAnswer.padding = UIEdgeInsets.init(top: CGFloat.zero, left: CGFloat(8), bottom: CGFloat.zero, right: CGFloat(8))
//            knewCorrectAnswer.center = CGPoint(x: 50, y: 285)
            knewCorrectAnswer.translatesAutoresizingMaskIntoConstraints = false
            knewCorrectAnswer.layer.borderColor = UIColor.black.cgColor
            knewCorrectAnswer.layer.borderWidth = 1.0
            knewCorrectAnswer.sizeToFit()
            knewCorrectAnswer.layer.masksToBounds = true
            knewCorrectAnswer.layer.cornerRadius = knewCorrectAnswer.frame.height / 2

//            knewCorrectAnswer.ed = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)

            knewCorrectAnswer.frame.size.width = knewCorrectAnswer.intrinsicContentSize.width + 10
            knewCorrectAnswer.frame.size.height = knewCorrectAnswer.intrinsicContentSize.height + 10
            knewCorrectAnswer.textAlignment = .center

            let tap = UITapGestureRecognizer(target: self, action: #selector(knewAnswerAction))
            knewCorrectAnswer.isUserInteractionEnabled = true
            knewCorrectAnswer.addGestureRecognizer(tap)
        }
        questionBG.addSubview(knewCorrectAnswer)
        knewCorrectAnswer.rightAnchor.constraint(equalTo: (correctedAnswer.leftAnchor),constant: -50).isActive = true
        knewCorrectAnswer.bottomAnchor.constraint(equalTo: (correctedAnswer.bottomAnchor),constant: 0).isActive = true
        
    }
    
    @objc
    private func knewAnswerAction(sender: customRectLabel){
        questionBG.subviews.forEach({ $0.removeFromSuperview() })
        bgView.subviews.forEach({ $0.removeFromSuperview() })
        bgView.removeFromSuperview()
        saveAnswerData()
        isQuestionShown = false
        showHideVideoControllers()
        
        DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
            self.questionsTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector:#selector(self.initQuestionsTimers),userInfo: nil, repeats: true)
            self.questionsTimer.fire()
        }
    }
    
    private func fillRadioButtonList(answersChecked : Bool = false){

        var constConstraint = 75
        if(answersChecked)
            {
            questionBG.subviews.forEach({ $0.alpha = 0 })
                
//            questionBG.subviews.forEach({ $0.removeFromSuperview() })
//            bgView.subviews.forEach({ $0.removeFromSuperview() })
            setQuestionTitle()
            let studentAnswer = questionsList[currentQuestion].questionBankAnswers[selectedAnswerIndex!].isCorrect!;
            if(studentAnswer)
            {
                knewAnswer(answerResult: true)
            }
            else{
                knewAnswer(answerResult: false)
            }

            }

        for (index, item) in questionsList[currentQuestion].questionBankAnswers.enumerated() {

            let radioButton = CustomButton(type: .custom);
            radioButton.semanticContentAttribute = .forceRightToLeft

            if(answersChecked)
            {
                if(item.isCorrect!)
                {
                    radioButton.setImage(UIImage(named: "correct"), for: .normal)
                }
                else
                {
                    radioButton.setImage(UIImage(named: "wrong"), for: .normal)
                }
                
            }
            else{
                radioButton.setImage(UIImage(named: "Radio_Unselected"), for: .normal)
                radioButton.addTarget(self, action: #selector(onRadioButtonTap), for: .touchUpInside)
                radioButton.selectedAnswerIndex = index;
            }
            radioButton.imageEdgeInsets = UIEdgeInsets(
             top: 0,
             left: 4,
             bottom: 0,
             right: 4
            )
            radioButton.setTitle(" " + questionsList[currentQuestion].questionBankAnswers[index].questionAnswerBody! + " ", for: .normal)
            radioButton.setTitleColor(UIColor.black, for: .normal)
            radioButton.sizeToFit()
            radioButton.contentEdgeInsets = UIEdgeInsets(top: 8, left: 16, bottom: 4, right: 16)


//            radioButton.frame = CGRect(fx: xOffset, y: 0.0, width: radioButton.intrinsicContentSize.width + 18, height: 40)
            radioButton.translatesAutoresizingMaskIntoConstraints = false

            questionBG.addSubview(radioButton)

            radioButton.rightAnchor.constraint(equalTo: (self.questionBG.rightAnchor),constant: -20).isActive = true
            radioButton.topAnchor.constraint(equalTo: (self.questionBG.topAnchor),constant: CGFloat(constConstraint)).isActive = true
      
            constConstraint = constConstraint + 50
            

        }
        
        
//        if(answersChecked)
//        {
//            var studentAnswer = questionsList[currentQuestion].questionBankAnswers[selectedAnswerIndex!].isCorrect!;
//            setQuestionTitle()
//            knewAnswer(answerResult: studentAnswer)
//        }
         
    }
    
    @objc
    private func fillCheckButtonList(answersChecked : Bool = false){

        var constConstraint = 75
        if(answersChecked)
            {
            questionBG.subviews.forEach({ $0.removeFromSuperview() })
//            bgView.subviews.forEach({ $0.removeFromSuperview() })
            setQuestionTitle()
            for(item) in multipleSelectedAnswerIndex{
                
                let selectedCount = multipleSelectedAnswerIndex.count
                
                let answersCount = questionsList[currentQuestion].questionBankAnswers.filter ({ PopUpQuestionAnswersModel in PopUpQuestionAnswersModel.isCorrect!}).count
                
                let studentAnswer = questionsList[currentQuestion].questionBankAnswers[item].isCorrect!
                
                
                if(studentAnswer  && selectedCount == answersCount)
                {
                    knewAnswer(answerResult: true)
                    break
                }
                else{
                    knewAnswer(answerResult: false)
                    break
                }
            }
            multipleSelectedAnswerIndex = [Int]()
            }
        else{
            var saveAnswer = UILabel()
           
            if let font =  UIFont(name: "Verdana", size: 16) {

                let textFontAttributes = [
                    NSAttributedString.Key.font : font,
                    NSAttributedString.Key.foregroundColor: UIColor.black,
                    NSAttributedString.Key.strokeColor: UIColor.black,
                ] as [NSAttributedString.Key : Any]

                let myMutableString : NSMutableAttributedString
                if(appLanguage == "ar")
                {
                    myMutableString = NSMutableAttributedString(string: "تأكد من الاجابة"  , attributes: textFontAttributes)
                }
                else
                {
                    myMutableString = NSMutableAttributedString(string: "Submit Answer"  , attributes: textFontAttributes)

                }

                
                saveAnswer =  customRectLabel(withInsets: 5, 5, 10, 10);
                
//                (frame: CGRect(origin: CGPoint(x:0, y:0), size: CGSize(width: 300, height: 60)))
                saveAnswer.attributedText = myMutableString
    //            knewCorrectAnswer.padding = UIEdgeInsets.init(top: CGFloat.zero, left: CGFloat(8), bottom: CGFloat.zero, right: CGFloat(8))
    //            knewCorrectAnswer.center = CGPoint(x: 50, y: 285)
                saveAnswer.translatesAutoresizingMaskIntoConstraints = false
                saveAnswer.layer.borderColor = UIColor.black.cgColor
                saveAnswer.layer.borderWidth = 1.0
                saveAnswer.sizeToFit()
                saveAnswer.layer.masksToBounds = true
                saveAnswer.layer.cornerRadius = saveAnswer.frame.height / 2
//                saveAnswer.padding = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)

    //            knewCorrectAnswer.ed = UIEdgeInsets(top: 5, left: 10, bottom: 5, right: 10)

                saveAnswer.frame.size.width = saveAnswer.intrinsicContentSize.width + 10
                saveAnswer.frame.size.height = saveAnswer.intrinsicContentSize.height + 10
                saveAnswer.textAlignment = .center

                let tap = UITapGestureRecognizer(target: self, action: #selector(onMultiSelectSubmitted))
                saveAnswer.isUserInteractionEnabled = true
                saveAnswer.addGestureRecognizer(tap)
            }
            questionBG.addSubview(saveAnswer)
            saveAnswer.rightAnchor.constraint(equalTo: ((self.questionBG.rightAnchor)),constant: -20).isActive = true
            saveAnswer.bottomAnchor.constraint(equalTo: (self.questionBG.bottomAnchor),constant: -20).isActive = true
        }

        for (index, item) in questionsList[currentQuestion].questionBankAnswers.enumerated() {

            let checkbox = CustomButton.init(type: .custom)
            checkbox.setImage(UIImage.init(named: "unchecked"), for: .normal)
            checkbox.setImage(UIImage.init(named: "checked"), for: .selected)
            checkbox.addTarget(self, action: #selector(self.toggleCheckboxSelection), for: .touchUpInside)
            checkbox.semanticContentAttribute = .forceRightToLeft

            if(answersChecked)
            {
                if(item.isCorrect!)
                {
                    checkbox.setImage(UIImage(named: "correct"), for: .normal)
                }
                else
                {
                    checkbox.setImage(UIImage(named: "wrong"), for: .normal)
                }
                
            }
            else
            {
                checkbox.selectedAnswerIndex = index
            }

            checkbox.imageEdgeInsets = UIEdgeInsets(
             top: 0,
             left: 4,
             bottom: 0,
             right: 4
            )
            checkbox.setTitle(" " + questionsList[currentQuestion].questionBankAnswers[index].questionAnswerBody! + " ", for: .normal)
            checkbox.setTitleColor(UIColor.black, for: .normal)
            checkbox.sizeToFit()
            checkbox.contentEdgeInsets = UIEdgeInsets(top: 8, left: 8, bottom: 4, right: 8)

            checkbox.translatesAutoresizingMaskIntoConstraints = false

            questionBG.addSubview(checkbox)

            checkbox.rightAnchor.constraint(equalTo: (self.questionBG.rightAnchor),constant: -20).isActive = true
            checkbox.topAnchor.constraint(equalTo: (self.questionBG.topAnchor),constant: CGFloat(constConstraint)).isActive = true
      
            constConstraint = constConstraint + 50
            

        }
        
         
    }
    
    @objc
    private func onRadioButtonTap(sender: CustomButton){
        selectedAnswerIndex = sender.selectedAnswerIndex
        fillRadioButtonList(answersChecked: true)
        
    }
    

    @objc func toggleCheckboxSelection(sender: CustomButton) {
        sender.isSelected = !sender.isSelected
        if(sender.isSelected)
        {
            multipleSelectedAnswerIndex.append(sender.selectedAnswerIndex!)
        }
        else
            {
            multipleSelectedAnswerIndex.removeAll( where:{ $0 ==  sender.selectedAnswerIndex!}
            )
            }

//        fillCheckButtonList(answersChecked: true)
    }
    
    @objc func onMultiSelectSubmitted(sender: UILabel) {
        fillCheckButtonList(answersChecked: true)
    }
    
    func addCuePoint() {
            
        
        setup.playbackService.findVideo(withVideoID: videoId, parameters: nil)
            { [weak self] (video: BCOVVideo?, jsonResponse: [AnyHashable: Any]?, error: Error?) -> Void in
                

                guard let durationNumber = video!.properties["duration"] as? NSNumber else {
                                return
                            }
                let duration = durationNumber.floatValue / 1000.0; // convert to seconds

        if let video = video {
             
                                
                let updatedVideo = video.update({ (mutableVideo: BCOVMutableVideo?) in

                    guard let mutableVideo = mutableVideo else {
                        return
                    }
                    
                        // Add quarterly interval cue points of your own type
                                        let cp1Position = CMTimeMake(value: Int64(duration * 250), timescale: 1000)
                                        let cp1 = BCOVCuePoint(type: "CODE", position: cp1Position)!
                                        let cp2Position = CMTimeMake(value: Int64(duration * 500), timescale: 1000)
                                        let cp2 = BCOVCuePoint(type: "CODE", position: cp2Position)!
                                        let cp3Position = CMTimeMake(value: Int64(duration * 750), timescale: 1000)
                                        let cp3 = BCOVCuePoint(type: "CODE", position: cp3Position)!
                                        let cp4Position = CMTimeMake(value: Int64(duration * 1000), timescale: 1000)
                                        let cp4 = BCOVCuePoint(type: "CODE", position: cp4Position)!
                                        
   
                    
                    // Create new cue point collection using existing cue points and new cue points
                                   var newCuePoints = [BCOVCuePoint]()
                                   newCuePoints.append(cp1)
                                   newCuePoints.append(cp2)
                                   newCuePoints.append(cp3)
                                   newCuePoints.append(cp4)
                                   
                                   mutableVideo.cuePoints = BCOVCuePointCollection(array: newCuePoints)
                    
                
                    
                })
            
                self?.playbackController?.setVideos([updatedVideo] as NSFastEnumeration)
            

            }
        }
            
        }

    public func destroy() {
        self.playbackController = nil
        self.nowPlayingHandler = nil
        self.videoId = nil

        if self.currentSession != nil && self.playbackController != nil {
            self.currentSession?.player.replaceCurrentItem(with: nil)
            self.playbackController?.remove(self.nowPlayingHandler)
            self.playbackController?.pause()
        }
    }

     //Method to create a custom button
     private func createRadioButton(frame : CGRect, title : String, color : UIColor)  {
         let radioButton = UIButton(frame: frame);
         radioButton.titleLabel?.translatesAutoresizingMaskIntoConstraints = false
         radioButton.titleLabel!.font = UIFont.systemFont(ofSize: 14);
         radioButton.setTitle(title, for: []);
         radioButton.setTitleColor(UIColor.darkGray, for: []);
         self.view.addSubview(radioButton);
     }
}

@available(iOS 12.0, *)
extension BrightcoveVideoPlayerViewController: BCOVPlaybackControllerDelegate {

    public func playbackController(_ controller: BCOVPlaybackController!, didCompletePlaylist playlist: NSFastEnumeration!) {
        let callback = {() -> Void in
            self.completedFired = true;
            // NotificationCenter.default.post(
            //     name: Notification.Name("videoClosed"),
            //     object: nil, userInfo: [
            //         "completed": true,
            //         "currentMillis": self.currentProgressMillis,
            //         "totalMillis": Int(self.duration!) * 1000,
            //         "subtitle": self.subtitle ?? ""
            //     ]
            // )
        }

        //self.dismiss(animated: false, completion: callback);
    }

    public func playbackController(_ controller: BCOVPlaybackController!, didAdvanceTo session: BCOVPlaybackSession!) {
        self.currentSession = session
        self.setupNowPlayingHandler()
    }

    public func playbackController(_ controller: BCOVPlaybackController!, playbackSession session: BCOVPlaybackSession!, didProgressTo progress: TimeInterval) {
         if(session.player.currentItem != nil) {
            let durationConversion =  CMTimeGetSeconds(session.player.currentItem!.duration)
                       
        if(!durationConversion.isNaN) {
             self.duration = durationConversion
           }
        }

        if(progress.isFinite) {
            self.currentProgressMillis = Int(progress * 1000)
            self.videoPositionChangeEvent()
        }

        currentProgress = progress
    }
    
    public func playbackController(_ controller: BCOVPlaybackController!, playbackSession session: BCOVPlaybackSession!, didChangeSelectedLegibleMediaOption legibleMediaOption: AVMediaSelectionOption!) {
        if(self.readyToUpdateSubtitle) {
            self.subtitle = legibleMediaOption?.extendedLanguageTag ?? ""
        }
    }

    public func playbackController(_ controller: BCOVPlaybackController!,playbackSession session: BCOVPlaybackSession!,didReceive event: BCOVPlaybackSessionLifecycleEvent) {
        if (kBCOVPlaybackSessionLifecycleEventReady == event.eventType) {
            self.readyToUpdateSubtitle = true
            // set subtitle
            if(self.subtitle != nil && session?.legibleMediaSelectionGroup != nil) {
                if let legibleMediaSelectionGroup = session?.legibleMediaSelectionGroup.options {
                    let locale = NSLocale(localeIdentifier: self.subtitle!) as Locale
                    let mediaSelectionOptions = AVMediaSelectionGroup.mediaSelectionOptions(from: legibleMediaSelectionGroup, with: locale)
                    let mediaSelectionOption = mediaSelectionOptions.first
                    session?.selectedLegibleMediaOption = mediaSelectionOption
                }
            }

            // set start to position
            if(self.startPosition != 0) {
                session.player.seek(
                    to: CMTimeMake(value: Int64(self.startPosition), timescale: 1000),
                    toleranceBefore: CMTime.zero,
                    toleranceAfter: CMTime.zero,
                    completionHandler: { (isFinished:Bool) -> Void in
                        if(!self.closeVideoCalled) {
                            session.player.play()
                        }
                    }
                )
            }
        }
    }

    private func videoPositionChangeEvent() {

        if(!self.isQuestionShown){
        if self.duration != nil {
            NotificationCenter.default.post(
                name: Notification.Name("videoPositionChange"),
                object: nil,
                userInfo: [
                    "currentMillis":  self.currentProgressMillis,
                    "totalMillis": Int(self.duration!) * 1000
                ]
            )

        }
        }

    }
}

@available(iOS 12.0, *)
extension BrightcoveVideoPlayerViewController: BCOVPUIPlayerViewDelegate {

    public func playerView(_ playerView: BCOVPUIPlayerView!, willTransitionTo screenMode: BCOVPUIScreenMode) {
        // Quit player as soon as we leave fullscreen
        if (screenMode == .normal) {
            self.playbackController!.pause()
            self.closeVideo()
        }
    }
}

func hexStringToUIColor (hex:String) -> UIColor {
    var cString:String = hex.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        return UIColor.gray
    }

    var rgbValue:UInt64 = 0
    Scanner(string: cString).scanHexInt64(&rgbValue)

    return UIColor(
        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
        alpha: CGFloat(1.0)
    )
}

class CustomButton : UIButton {
    var selectedAnswerIndex : Int?
}

class customRectLabel: UILabel {
    
    var topInset: CGFloat
     var bottomInset: CGFloat
     var leftInset: CGFloat
     var rightInset: CGFloat

     required init(withInsets top: CGFloat, _ bottom: CGFloat,_ left: CGFloat,_ right: CGFloat) {
         self.topInset = top
         self.bottomInset = bottom
         self.leftInset = left
         self.rightInset = right
         super.init(frame: CGRect.zero)
     }

     required init?(coder aDecoder: NSCoder) {
         fatalError("init(coder:) has not been implemented")
     }

     override func drawText(in rect: CGRect) {
         let insets = UIEdgeInsets(top: topInset, left: leftInset, bottom: bottomInset, right: rightInset)
         super.drawText(in: rect.inset(by: insets))
     }
    override var intrinsicContentSize: CGSize {
          get {
              var contentSize = super.intrinsicContentSize
              contentSize.height += topInset + bottomInset
              contentSize.width += leftInset + rightInset
              return contentSize
          }
      }
  }
//    override func drawText(in rect: CGRect) {
//        let context = UIGraphicsGetCurrentContext()!
//        context.stroke(self.bounds.insetBy(dx: 1.0, dy: 1.0))
//        super.drawText(in: rect.insetBy(dx: 10, dy: 10))
//    }
//
//    public var edgeInset = UIEdgeInsets(top: 8,left: 24,bottom: 8,right: 24)
//
//       override func drawText(in rect: CGRect) {
//           let insets = UIEdgeInsets.init(top: edgeInset.top, left: edgeInset.left, bottom: edgeInset.bottom, right: edgeInset.right)
//           super.drawText(in: rect.inset(by: insets))
//       }
//
//       override var intrinsicContentSize: CGSize {
//           let size = super.intrinsicContentSize
//           return CGSize(width: size.width + edgeInset.left + edgeInset.right, height: size.height + edgeInset.top + edgeInset.bottom)
//       }
//}

extension UIColor {
    convenience init(hexString: String) {
        let hex = hexString.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
        var int = UInt64()
        Scanner(string: hex).scanHexInt64(&int)
        let a, r, g, b: UInt64
        switch hex.count {
        case 3: // RGB (12-bit)
            (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
        case 6: // RGB (24-bit)
            (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
        case 8: // ARGB (32-bit)
            (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
        default:
            (a, r, g, b) = (255, 0, 0, 0)
        }
        self.init(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: CGFloat(a) / 255)
    }
}
