//
//  LNRoomBottomMicView.swift
//  Gami
//
//  Created by OneeChan on 2026/3/17.
//

import Foundation
import UIKit
import AtomicXCore
import Combine


class LNRoomBottomMicView: UIButton {
    private weak var roomSession: LNRoomSession?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupViews()
        LNEventDeliver.addObserver(self)
    }
    
    func update(_ room: LNRoomSession?) {
        roomSession = room
        
        if let room {
            onRoomSeatsChanged(session: room, changed: room.seatsInfo)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension LNRoomBottomMicView: LNRoomViewModelNotify {
    func onRoomSeatsChanged(session: LNRoomSession, changed: [LNRoomSeatItem]) {
        guard roomSession == session else { return }
        if let seat = roomSession?.mySeatInfo {
            isHidden = false
            if seat.isMute {
                setBackgroundImage(.icMicOffWhite15, for: .normal)
                isEnabled = false
            } else {
                isEnabled = true
                if seat.isLocalMute {
                    setBackgroundImage(.icMicOffWhite15, for: .normal)
                } else {
                    setBackgroundImage(.icMicOn, for: .normal)
                }
            }
        } else {
            isHidden = true
        }
    }
}

extension LNRoomBottomMicView {
    private func setupViews() {
        setBackgroundImage(.icMicOn, for: .normal)
        addAction(UIAction(handler: { [weak self] _ in
            guard let self else { return }
            if roomSession?.mySeatInfo?.isLocalMute == true {
                roomSession?.unmuteMySeat { _ in }
            } else {
                roomSession?.muteMySeat()
            }
        }), for: .touchUpInside)
    }
}
