//
//  RttChartsViewController.swift
//  MpAccDemo
//
//  Created by Robin on 2024/12/27.
//

import UIKit
import DGCharts
import SnapKit
import MpAccSDK

class RttChartsViewController: UIViewController {
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton(type: .close)
        btn.backgroundColor = .white
        btn.layer.cornerRadius = 20
        btn.addTarget(self, action: #selector(closeAction(sender:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var lineChartView: LineChartView = {
        let chatView = LineChartView()
        chatView.backgroundColor = .black
        chatView.rightAxis.enabled = false
        chatView.legend.textColor = .white
        
        let yAxis = chatView.leftAxis
        yAxis.labelFont = .boldSystemFont(ofSize: 12)
        yAxis.setLabelCount(6, force: false)
        yAxis.labelTextColor = .green
        yAxis.axisLineColor = .yellow
        yAxis.axisLineWidth = 3
        yAxis.labelPosition = .outsideChart
        
        chatView.xAxis.labelPosition = .bottom
        chatView.xAxis.labelTextColor = .green
        chatView.xAxis.axisLineColor = .yellow
        chatView.xAxis.axisLineWidth = 3
        return chatView
    }()

    lazy var lineRttData: ChartRttData = ChartRttData()
    
    init() {
        super.init(nibName: nil, bundle: nil)
        self.modalPresentationStyle = .fullScreen
    }
    
    required init?(coder: NSCoder) {
        fatalError("")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .black
        
        self.view.addSubview(self.lineChartView)
        self.view.addSubview(self.closeBtn)
        
        self.lineChartView.snp.makeConstraints { make in
            make.edges.equalTo(self.view.safeAreaLayoutGuide)
        }
        self.closeBtn.snp.makeConstraints { make in
            make.right.top.equalTo(self.view.safeAreaLayoutGuide).inset(10)
            make.size.equalTo(40)
        }
        
        self.lineRttData.bindDataToChartView(self.lineChartView)
        
        MpAccClient.shared.registerMeasureCallback(self)
    }
    
    @objc func closeAction(sender: UIButton) {
        self.dismiss(animated: true)
    }
    
    override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
        .landscapeRight
    }
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        .landscapeRight
    }
}

extension RttChartsViewController: MpMeasureCallback {
    func onRttChanged(type: Int, rtt: Int) {
        self.lineRttData.orgRttData.updateRtt(rtt, type: type)
    }
}
