//
//  AudioRecorderHelper.swift
//  WoWonder
//
//  Created by iMac on 18/08/23.
//  Copyright © 2023 ScriptSun. All rights reserved.
//

import Foundation
import AVFoundation
import UIKit

protocol AudioRecorderHelperDelegate: AnyObject {
    func audioRecordingFinished(success: Bool, audioURL: URL?)
}

class AudioRecorderHelper: NSObject, AVAudioRecorderDelegate {
    
    weak var delegate: AudioRecorderHelperDelegate?
    
    var audioRecorder: AVAudioRecorder?
    var isRecording = false
    
    override init() {
        super.init()
        setupAudioRecorder()
    }
    
    func setupAudioRecorder() {
        let audioFilename = getDocumentsDirectory().appendingPathComponent("audioRecording.wav")
        
        let settings: [String : Any] = [
            AVFormatIDKey: Int(kAudioFormatLinearPCM),
            AVSampleRateKey: 44100.0,
            AVNumberOfChannelsKey: 1,
            AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
        ]
        
        do {
            audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
            audioRecorder?.delegate = self
            audioRecorder?.prepareToRecord()
        } catch {
            print("Error setting up audio recorder: \(error.localizedDescription)")
        }
    }
    
    func startRecording() {
        checkMicrophonePermission { [weak self] granted in
            guard let self = self else { return }
            if granted {
                if !self.isRecording {
                    let audioSession = AVAudioSession.sharedInstance()
                    do {
                        try audioSession.setActive(true)
                        self.audioRecorder?.record()
                        self.isRecording = true
                    } catch {
                        print("Error starting recording: \(error.localizedDescription)")
                    }
                }
            } else {
                DispatchQueue.main.async {
                    guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else { return }
                    if UIApplication.shared.canOpenURL(settingsURL) {
                        UIApplication.shared.open(settingsURL)
                    }
                }
            }
        }
    }
    
    func stopRecording() {
        if isRecording {
            audioRecorder?.stop()
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(false)
                isRecording = false
            } catch {
                print("Error stopping recording: \(error.localizedDescription)")
            }
        }
    }
    
    func cancelRecording() {
        if isRecording {
            audioRecorder?.stop()
            audioRecorder?.deleteRecording()
            let audioSession = AVAudioSession.sharedInstance()
            do {
                try audioSession.setActive(false)
                isRecording = false
            } catch {
                print("Error canceling recording: \(error.localizedDescription)")
            }
        }
    }
    
    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
        if flag {
            delegate?.audioRecordingFinished(success: true, audioURL: recorder.url)
        } else {
            delegate?.audioRecordingFinished(success: false, audioURL: nil)
        }
    }
    
    private func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    
    func checkMicrophonePermission(completion: @escaping (Bool) -> Void) {
        AVAudioSession.sharedInstance().requestRecordPermission { granted in
            completion(granted)
        }
    }
    
}
