//
//  ViewController.swift
//  RecordingAudio
//
//  Created by Keith Welch on 12/4/15.
//  Copyright © 2015 Keith Welch. All rights reserved.
//

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioRecorderDelegate, AVAudioPlayerDelegate {

    @IBOutlet weak var txtFilename: UITextField!
    @IBOutlet weak var btnRecord: UIButton!
    @IBOutlet weak var btnStop: UIButton!
    
    var recorder: AVAudioRecorder!
    var audioPlayer:AVAudioPlayer!
    var audioFile: NSString!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        btnRecord.enabled = true
        btnStop.enabled = false
    }

    @IBAction func btnRecordTouched(sender: AnyObject) {
        if ((recorder == nil) || !recorder.recording)
        {
            btnRecord.enabled = false
            btnStop.enabled = true
            initRecorder(txtFilename.text!)
            recorder.record()
        }
    }
    
    func initRecorder(fileName: String) {
        let paths:NSArray = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0] as! NSString
        audioFile = documentsDirectory.stringByAppendingPathComponent(fileName)
        let url = NSURL.fileURLWithPath(audioFile as String)

        let recordSettings = [
            AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
            AVSampleRateKey: 12000.0,
            AVNumberOfChannelsKey: 1 as NSNumber,
            AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
        ]
        
        do {
            recorder = try AVAudioRecorder(URL: url, settings: recordSettings)
            recorder.delegate = self
            recorder.meteringEnabled = true
            recorder.prepareToRecord() // creates/overwrites the file at soundFileURL
        } catch let error as NSError {
            recorder = nil
            print(error.localizedDescription)
        }
    }
    
    func audioRecorderDidFinishRecording(recorder: AVAudioRecorder, successfully flag: Bool) {
        let url = NSURL.fileURLWithPath(audioFile as String)
        
        do {
            try audioPlayer = AVAudioPlayer(contentsOfURL: url)
            audioPlayer.delegate = self
            audioPlayer.play()
            
        } catch {
            NSLog("Player not available")
        }

    }
    
    func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder, error: NSError?) {
        btnRecord.enabled = true
        btnStop.enabled = false
        NSLog(error!.description)
    }

    @IBAction func btnStopTouched(sender: AnyObject) {
        btnRecord.enabled = true
        btnStop.enabled = false
        
        if (recorder.recording)
        {
            recorder.stop()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

