//
//  ViewController.swift
//  MultiInstancesApp
//
//  Created by Abdul on 07/03/19.
//  Copyright © 2019 Abdul. All rights reserved.
//

import UIKit
import AVKit
import CoreLocation
import AdSupport
import AVFoundation
import NielsenAppApi

class ViewController: UIViewController, NielsenAppApiDelegate, AVPlayerViewControllerDelegate {
    
    @IBOutlet weak var lblAppId: UILabel!
    @IBOutlet weak var lblAppName: UILabel!
    
    var nielsenMain : NielsenAppApi!
    var nielsenApi : NielsenAppApi!
    var videoType : Int!
    var player : AVPlayer!
    var controller : AVPlayerViewController!
    var sdkMethods : SDKMethods!
    var totalVideosPlayed = 0
    
    var data : [String : Any]!
    var timeObserver: Any!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        //Mark: In SDKMethods class we wrote methods which creates content,Ad,DTVR objects
        sdkMethods = SDKMethods()
        
        let notificationCenter = NotificationCenter.default
        notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
        
        if(videoType == Constants.subBrandA){
            self.view.backgroundColor = UIColor(patternImage: UIImage(named: "space6")!)
            
            lblAppId.text = "App Id : PE4A57F64-878D-4D69- 8EFB-4E87C27BA7A4"
            
            lblAppName.text = "staticData =\n[\n    'type': 'static\n    'assetid' : 'AAA11111'\n    'section': 'SubBrand-A'\n    'segA': 'segmentA'\n    'segB': 'segmentB\n    'segC': 'segmentC'\n]"
        
            self.data = sdkMethods.loadStaticSubbrandA()
            
            NSLog("Fired Sub Brand A Static Event")
            
            //loading video content url
            sdkMethods.setContentSubAUrl()
            
        }else{
       
            let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
            backgroundImage.image = UIImage(named: "space7")
            backgroundImage.contentMode = UIView.ContentMode.scaleAspectFill
            self.view.insertSubview(backgroundImage, at: 0)
           
            
            lblAppId.text = "App Id : PDA7D5EE6-B1B8-4123-9277-2A788BC653CA"
            
            lblAppName.text = "staticData =\n[\n    'type': 'static\n    'assetid' : 'AAA11111'\n    'section': 'SubBrand-B'\n    'segA': 'segmentA'\n    'segB': 'segmentB\n    'segC': 'segmentC'\n]"
            
            self.data = sdkMethods.loadStaticSubbrandB()
          
            NSLog("Fired Sub Brand B Static Event")
            
            //loading video content url
            sdkMethods.setContentSubBUrl()
        }
       
        setPlayer()
        
        setPlayHeadPosition()
        
        //Setting observer to know the completion of video
        setVideoFinishObserver()
    }
    
    
    @objc func appMovedToBackground() {
        print("App moved to background!")
        
        let mainData = sdkMethods.loadStaticMaster()
        nielsenMain.loadMetadata(mainData)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        
        nielsenApi.loadMetadata(data)
    }
    
    func setPlayer() {
        
        //creating player
        player  = AVPlayer.init(url: sdkMethods.url! as URL)
        controller = AVPlayerViewController()
        controller.view.frame = CGRect(x:0 , y:100, width: self.view.frame.width, height: 300)
        controller.player = player;
        controller.showsPlaybackControls = true;
        controller.delegate = self;
        
        
        //Adding observer to player to track play,pause.
        player.addObserver(self, forKeyPath: "rate", options: NSKeyValueObservingOptions.new, context: nil)
        
        //Only for DTVR videos we are tracking iD3 Tags and sends to SDK after extracting.
        self.addChild(controller)
        self.view.addSubview(controller.view)
    }
    
    func setPlayHeadPosition() {
        //Setting play head position
        let timeInterval : CMTime = CMTimeMakeWithSeconds(1.0, preferredTimescale: 10)
        controller.player?.addPeriodicTimeObserver(forInterval: timeInterval, queue: DispatchQueue.main) {(elapsedTime: CMTime) -> Void in
            
            let time : Float64 = self.controller.player!.currentTime().seconds;
            let pos = Int64(time);
            //Sending playHeadPosition to SDK.
            self.nielsenApi?.playheadPosition(pos);
        }
    }
    
    func setVideoFinishObserver() {
        //observer fires on completion video.
        NotificationCenter.default.addObserver(self, selector: #selector(playerDidFinishPlaying), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: controller.player?.currentItem)
    }
    
    //rate 0.0 = Video Pause or stopped
    //rate 1.0 = Video played or resumed
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        if keyPath == "rate" {
            if let rate = change?[NSKeyValueChangeKey.newKey] as? Float {
                
                if rate == 0.0 {
                    print("Playback stopped")
                    //On Video pause calling the "stop" method of SDK.
                    nielsenApi.stop()
                }
                if rate == 1.0 {
                    print("normal playback")
                    
                    if(totalVideosPlayed == 0){
                        
                        //For first time sending Channel info to SDK using "play" method.
                        nielsenApi.play(sdkMethods.loadChannelInfo())
                        
                        
                        //loading video content metadata data
                        if(videoType == Constants.subBrandA){
                            
                            self.data = sdkMethods.loadContentSubA()
                            
                        }else{
                            
                            self.data = sdkMethods.loadContentSubB()
                        }
                        
                        totalVideosPlayed += 1
                        
                    }
                    
                    //On video Resume calling "loadMetada" method of SDK
                    nielsenApi.loadMetadata(self.data)
                }
            }
        }
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        
        //On moving to other screen calling "stop" method of SDK.
        //Checking if video is played or not
        if(player.rate > 0){
            nielsenApi.stop()
            player.rate = 0
            player.pause()
           
        }
    }
    
    @objc func playerDidFinishPlaying(note: NSNotification) {
        
        self.player?.removeObserver(self, forKeyPath: "rate")
        
        nielsenApi.end()
        
    }
    
    deinit {
        
        print("Remove NotificationCenter Deinit")
        NotificationCenter.default.removeObserver(self)
    }
    
}


