//
//  YHSimpleAudienceVC.swift
//  galaxy
//
//  Created by alexzzw on 2024/11/30.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import AgoraRtcKit
import UIKit

class YHSimpleAudienceVC: UIViewController {
    // MARK: - Properties
    private var agoraKit: AgoraRtcEngineKit!
    private var isJoined: Bool = false
    private var remoteView: UIView!
    private let viewModel = YHLiveSalesViewModel()
    private let liveId: Int = 40
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupAgoraKit()
        joinChannel()
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        leaveChannel()
    }
    
    // MARK: - Setup
    private func setupUI() {
        // Setup remote video view
        remoteView = UIView()
        view.addSubview(remoteView)
        remoteView.frame = view.bounds
        remoteView.backgroundColor = .black
    }
    
    private func setupAgoraKit() {
        // Initialize AgoraRtcEngineKit
        let config = AgoraRtcEngineConfig()
        config.appId = YhConstant.AgoraRtcKit.appId
        config.channelProfile = .liveBroadcasting
        
        agoraKit = AgoraRtcEngineKit.sharedEngine(with: config, delegate: self)
        
        // Enable video
        agoraKit.enableVideo()
        
        // Set client role as audience
        let options = AgoraClientRoleOptions()
        options.audienceLatencyLevel = .lowLatency
        agoraKit.setClientRole(.audience, options: options)
        
        // Set audio route to speaker
        agoraKit.setDefaultAudioRouteToSpeakerphone(true)
    }
    
    // MARK: - Channel
    private func joinChannel() {
        // Create media options
        let option = AgoraRtcChannelMediaOptions()
        option.publishCameraTrack = false
        option.publishMicrophoneTrack = false
        option.clientRoleType = .audience
        
        viewModel.getLiveDetail(id: liveId) { [weak self] liveDetail, _ in
            guard let self = self else {
                return
            }
            guard let liveDetail = liveDetail else {
                return
            }
            self.agoraKit.preloadChannel(byToken: liveDetail.token,
                                         channelId: liveDetail.rtmp_channel,
                                         uid: UInt(self.liveId))
            let result = self.agoraKit.joinChannel(byToken: liveDetail.token,
                                            channelId: liveDetail.rtmp_channel,
                                                   uid: UInt(self.liveId),
                                            mediaOptions: option)
            
            if result != 0 {
                print("Join channel failed: \(result)")
            }
        }
        
//        viewModel.generateToken(channelName: channelName, uid: 0) { [weak self] token in
//            guard let self = self else {
//                return
//            }
//            self.agoraKit.preloadChannel(byToken: token,
//                                         channelId: channelName,
//                                         uid: 0)
//            let result = self.agoraKit.joinChannel(byToken: token,
//                                            channelId: channelName,
//                                            uid: 0,
//                                            mediaOptions: option)
//            
//            if result != 0 {
//                print("Join channel failed: \(result)")
//            }
//        }
        
    }
    
    private func leaveChannel() {
        if isJoined {
            agoraKit.disableVideo()
            agoraKit.disableAudio()
            agoraKit.leaveChannel(nil)
            AgoraRtcEngineKit.destroy()
        }
    }
}

// MARK: - AgoraRtcEngineDelegate
extension YHSimpleAudienceVC: AgoraRtcEngineDelegate {
    // Called when successfully joined the channel
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinChannel channel: String, withUid uid: UInt, elapsed: Int) {
        isJoined = true
        print("Local user joined with uid \(uid)")
    }
    
    // Called when a remote user joins
    func rtcEngine(_ engine: AgoraRtcEngineKit, didJoinedOfUid uid: UInt, elapsed: Int) {
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        videoCanvas.view = remoteView
        videoCanvas.renderMode = .fit
        videoCanvas.backgroundColor = 0x000000
        agoraKit.setupRemoteVideo(videoCanvas)
    }
    
    // Called when a remote user leaves
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOfflineOfUid uid: UInt, reason: AgoraUserOfflineReason) {
        let videoCanvas = AgoraRtcVideoCanvas()
        videoCanvas.uid = uid
        videoCanvas.view = nil
        agoraKit.setupRemoteVideo(videoCanvas)
    }
    
    // Called when warning occurs
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurWarning warningCode: AgoraWarningCode) {
        print("Warning: \(warningCode.rawValue)")
    }
    
    // Called when error occurs
    func rtcEngine(_ engine: AgoraRtcEngineKit, didOccurError errorCode: AgoraErrorCode) {
        print("Error: \(errorCode.rawValue)")
    }
}
