//
//  ViewController.swift
//  DRMTodayDemo
//
//

import PRESTOplay
import CastlabsApple
import AVFoundation
import UIKit

class ViewController: UIViewController {
    // create player instance
    var player = PRESTOplaySDK.shared.player()
    
    lazy var playerConfiguration: PlayerConfiguration = {
        let hlsStream = "https://example.com/stream.m3u8"
        let playerConfig = PlayerConfiguration(with: URL(string: hlsStream)!)
        playerConfig.drmType = .custom
        playerConfig.drmSystem = .fairplay
        let drmConfig = DrmConfiguration()
        drmConfig.certificateUrl = URL(
            string: "...")!
        drmConfig.licensingUrl = URL(
            string: "...")!

        let dict = [
            "merchant": "...",
            "userId": "...",
            "sessionId": "..."
        ]
        if let customData = try? JSONSerialization.data(
            withJSONObject: dict,
            options: []) {
            drmConfig.licensingParameters = [
                "dt-custom-data": customData.base64EncodedString(),
                "Content-Type": "application/x-www-form-urlencoded"
            ]
        }
        playerConfig.drmConfiguration = drmConfig
        return playerConfig
    }()
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        // optional: ignore silent switch
        try? AVAudioSession.sharedInstance().setCategory(.playback)

        player.requestModifiers = [DRMTodayRequestModifier()]
        player.responseModifiers = [DRMTodayResponseModifier()]
        
        player.load(config: playerConfiguration)

        player.onState = { [weak self] previous, state in
            guard let self else { return }
            if let error = player.error {
                print("Error \(error)")
            }
        }

        player.attach(to: view.layer)
        player.open(autoplay: true)
    }

    override func viewWillTransition(to size: CGSize,
                                     with coordinator: UIViewControllerTransitionCoordinator) {
        player.update(size: size)
    }
}

// Prepare the license request for the DRMToday backend
struct DRMTodayRequestModifier: RequestModifierProtocol {
    func modify(_ request: Request,
                completionHandler: @escaping (Request?) -> Void) {
        guard request.type == .license else {
            completionHandler(request)
            return
        }

        let queryKeyValueString = CharacterSet(charactersIn: ":?=&+").inverted
        let encodedSpcMessage = request.data?.base64EncodedString()
            .addingPercentEncoding(
                withAllowedCharacters: queryKeyValueString) ?? ""
        
        let post = String(format: "spc=%@", encodedSpcMessage)

        request.data = post.data(using: .utf8, allowLossyConversion: true)
        completionHandler(request)
    }
}

// Parse the response returned from DRMToday backend
struct DRMTodayResponseModifier: ResponseModifierProtocol {
    func modify(_ response: Response,
                completionHandler: @escaping (Response?) -> Void) {
        guard response.type == .license else {
            completionHandler(response)
            return
        }

        response.data = Data(base64Encoded: response.data!)
        completionHandler(response)
    }
}
