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

import UIKit
import MediaPlayer
import AVFoundation

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var btnPlay: UIButton!
    @IBOutlet weak var lblSongName: UILabel!
    @IBOutlet weak var lblSongLength: UILabel!
    @IBOutlet weak var tblView: UITableView!
    
    var songFiles: NSMutableArray!
    var audioPlayer:AVPlayer!

    let cellID = "CellID"

    override func viewDidLoad() {
        super.viewDidLoad()

        btnPlay.setTitle("Play", forState: .Normal)
        btnPlay.setTitle("Stop", forState: .Selected)
        
        loadSongList()
        tblView.dataSource = self
        tblView.reloadData()
        
        let song: MPMediaItem = songFiles[0] as! MPMediaItem
        let url = song.assetURL

        let currentItem: AVPlayerItem = AVPlayerItem(URL: url!)
        audioPlayer = AVPlayer()
        audioPlayer.replaceCurrentItemWithPlayerItem(currentItem)
        
        lblSongName.text = song.title
        
        initPlayer()
    }
    
    func loadSongList() {
    // to get all songs:
        let everything: MPMediaQuery = MPMediaQuery()
        songFiles = NSMutableArray(array: everything.items!)
    
    // to filter songs:
//        let songNamePredicate: MPMediaPropertyPredicate = MPMediaPropertyPredicate(value: "U2", forProperty: MPMediaItemPropertyArtist, comparisonType: .Contains)
//
//        let songsQuery: MPMediaQuery = MPMediaQuery.songsQuery()
//        songsQuery.addFilterPredicate(songNamePredicate)
//    
//        songFiles = NSMutableArray(array: songsQuery.items!)
    }
    
    func initPlayer() {
        audioPlayer.addPeriodicTimeObserverForInterval(CMTimeMakeWithSeconds(1, 1), queue: dispatch_get_main_queue()) { (CMTime) -> Void in
            let currentTime = Int(self.audioPlayer.currentTime().value) / Int(self.audioPlayer.currentTime().timescale)
            let currentMins = currentTime / 60
            let currentSec  = currentTime % 60
            
            let durationLabel = String(format: "%02d:%02d", currentMins,currentSec)
            self.lblSongLength.text = durationLabel
        }
    }

    @IBAction func btnPlayTouched(sender: AnyObject) {
        if(btnPlay.selected) {
            audioPlayer.pause()
            btnPlay.selected = false
        } else {
            audioPlayer.play()
            btnPlay.selected = true
        }
    }

    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return songFiles.count;
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
        if cell == nil {
            cell = UITableViewCell(style: .Value1, reuseIdentifier: cellID)
        }

        let song: MPMediaItem = songFiles[indexPath.row] as! MPMediaItem
        cell!.textLabel!.text = song.title
        cell!.detailTextLabel!.text = song.artist

        return cell!
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        audioPlayer.pause()
        let song: MPMediaItem = songFiles[indexPath.row] as! MPMediaItem
        let url = song.assetURL
        
        let currentItem: AVPlayerItem = AVPlayerItem(URL: url!)
        audioPlayer.replaceCurrentItemWithPlayerItem(currentItem)
        audioPlayer.play()
        btnPlay.selected = true
        lblSongName.text = song.title
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

