import UIKit
import RxSwift
import PKHUD

class AudioRecordCell: UITableViewCell, ConfigurableCell {
    
    @IBOutlet weak var playButton: UIButton!
    @IBOutlet weak var duration: UILabel!
    @IBOutlet weak var number: UILabel!
    @IBOutlet weak var date: UILabel!
    @IBOutlet weak var progressView: CellProgressView!
    
    let dateFormatter = DateFormatter()
    let componentsFormatter = DateComponentsFormatter()
    var stateDisposable: Disposable?
    var progressDisposable: Disposable?
    
    var record: AudioRecord?

    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.dateFormatter.dateStyle = .short
        self.dateFormatter.timeStyle = .short
        
        self.componentsFormatter.unitsStyle = .abbreviated
        self.componentsFormatter.allowedUnits = [.minute, .second]
        self.componentsFormatter.zeroFormattingBehavior = .pad
        
        self.progressView.progress = 0
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
        self.record = nil
        self.stateDisposable?.dispose()
        self.progressDisposable?.dispose()
        self.progressView.progress = 0
    }
    
    func configure(with record: AudioRecord) {
        self.record = record
        self.date.text = self.dateFormatter.string(from: Date(timeIntervalSince1970: record.getAddedDate()))
        self.number.text = record.number ?? "Unrecognized"
        self.duration.text = self.componentsFormatter.string(from: record.duration)
        
        self.stateDisposable = AudioPlayer.shared
            .stateObservable()
            .filter { _ in AudioPlayer.shared.getUrl()?.lastPathComponent == record.path }
            .subscribe(onNext: { state in
                let imgName = state == .playing ? "pause.fill" : "play.fill"
                self.playButton.setImage(UIImage(systemName: imgName), for: .normal)
                
                if state == .stopped {
                    self.progressView.progress = 0
                }
            }, onDisposed: {
                self.playButton.setImage(UIImage(systemName: "play.fill"), for: .normal)
            })
        
        self.progressDisposable = AudioPlayer.shared
            .progressObservable()
            .filter { _ in AudioPlayer.shared.getUrl()?.lastPathComponent == record.path }
            .subscribe(onNext: { progress in
                self.progressView.progress = progress
            }, onDisposed: {
                self.progressView.progress = 0
            })
    }
    
    @IBAction func onPlay(_ sender: UIButton) {
        if let record = self.record {
            do {
                let url = try FileManager.default.url(for: record.path, in: "recordings")
                try AudioPlayer.shared.play(url: url)
            } catch {
                print("Error playing audio record: \(error.localizedDescription)")
                HUD.show(error: error)
            }
        }
    }
}
