//
//  RightAudioTableViewCell.swift
//  WoWonder
//
//  Created by Mac on 12/11/22.
//  Copyright © 2022 ScriptSun. All rights reserved.
//

import UIKit
import AVFAudio

class RightAudioTableViewCell: SwipeToReplyCell {
    
    @IBOutlet weak var cellView: UIView!
    @IBOutlet weak var messageView: UIView!
    @IBOutlet weak var forwardedView: UIView!
    @IBOutlet weak var replyStoryView: UIView!
    @IBOutlet weak var replyStoryBorderView: UIView!
    @IBOutlet weak var replyStoryTitleLabel: UILabel!
    @IBOutlet weak var replyStoryMessageLabel: UILabel!
    @IBOutlet weak var replyStoryImageView: UIImageView!
    @IBOutlet weak var reactionImageView: UIImageView!
    @IBOutlet weak var replyMessageView: UIView!
    @IBOutlet weak var replyUserLabel: UILabel!
    @IBOutlet weak var replyMessageLabel: UILabel!
    @IBOutlet weak var playButton: UIButton!
    @IBOutlet weak var audioSliderView: UISlider!
    @IBOutlet weak var audioDurationLabel: UILabel!
    @IBOutlet weak var audioView: UIView!
    @IBOutlet weak var messageTimeLabel: UILabel!
    @IBOutlet weak var starImageView: UIImageView!
    @IBOutlet weak var lastSeenImage: UIImageView!
    
    var audioURL: URL!
    var playButtonTapHandler: (() -> Void)?
    var timer: Timer?
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        self.messageView.clipsToBounds = true
        self.messageView.layer.cornerRadius = 16
        self.messageView.layer.maskedCorners = [.layerMaxXMaxYCorner, .layerMinXMaxYCorner, .layerMinXMinYCorner]
        self.audioSliderView.setThumbImage(UIImage(named: "right_slider_thumb"), for: .normal)
        self.audioSliderView.setThumbImage(UIImage(named: "right_slider_thumb"), for: .highlighted)
        self.playButton.setImage(UIImage(named: "icon_play_vector"), for: .normal)
    }
    
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
    // Play Button Action
    @IBAction func playButtonAction(_ sender: UIButton) {
        playButtonTapHandler?()
    }
    
    // Audio Slider Value Changed
    @IBAction func audioSliderValueChanged(_ sender: UISlider) {
        AudioPlayerHelper.shared.audioPlayer?.currentTime = TimeInterval(sender.value)
    }
    
    func setupAudioPlayer(url: URL, indexPath: IndexPath) {
        do {
            let soundData = try Data(contentsOf: url)
            let audioPlayer = try AVAudioPlayer(data: soundData)
            let durationInSeconds = Int(audioPlayer.duration)
            self.audioSliderView.minimumValue = 0
            self.audioSliderView.maximumValue = Float(audioPlayer.duration)
            if AudioPlayerHelper.shared.playingIndexPath == indexPath {
                if AudioPlayerHelper.shared.audioPlayer?.isPlaying == true {
                    self.timer = Timer.scheduledTimer(withTimeInterval: 0.01, repeats: true, block: { [weak self] timer in
                        guard let self = self else { return }
                        DispatchQueue.main.async {
                            if AudioPlayerHelper.shared.playingIndexPath == indexPath {
                                if AudioPlayerHelper.shared.audioPlayer?.isPlaying ?? false {
                                    self.audioSliderView.value = Float(AudioPlayerHelper.shared.audioPlayer?.currentTime ?? 0)
                                    self.audioDurationLabel.text = self.formatTime(AudioPlayerHelper.shared.audioPlayer?.currentTime ?? 0)
                                } else {
                                    timer.invalidate()
                                }
                            } else {
                                timer.invalidate()
                            }
                        }
                    })
                    self.playButton.setImage(UIImage(named: "icon_pause_vector"), for: .normal)
                } else {
                    self.audioSliderView.value = Float(AudioPlayerHelper.shared.audioPlayer?.currentTime ?? 0)
                    self.audioDurationLabel.text = self.formatTime(AudioPlayerHelper.shared.audioPlayer?.currentTime ?? 0)
                    self.playButton.setImage(UIImage(named: "icon_play_vector"), for: .normal)
                    self.timer?.invalidate()
                    self.timer = nil
                }
            } else {
                self.timer?.invalidate()
                self.timer = nil
                self.playButton.setImage(UIImage(named: "icon_play_vector"), for: .normal)
                self.audioSliderView.value = 0
                self.audioDurationLabel.text = String(format: "%02d:%02d", durationInSeconds / 60, durationInSeconds % 60)
            }
        } catch {
            print(error.localizedDescription)
        }
    }
    
    func formatTime(_ timeInterval: TimeInterval) -> String {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .positional
        formatter.allowedUnits = [.minute, .second]
        formatter.zeroFormattingBehavior = [.pad]
        return formatter.string(from: timeInterval) ?? "00:00"
    }
    
}
