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

import UIKit
import CoreMotion

class ViewController: UIViewController {
    @IBOutlet weak var lblAcceleration: UILabel!
    @IBOutlet weak var lblGyro: UILabel!

    var motionManager: CMMotionManager!
    var timer: NSTimer!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        motionManager = CMMotionManager()
        if (!motionManager.deviceMotionAvailable) {
            // Don't try to use it
        }
        else {
            motionManager.deviceMotionUpdateInterval = 0.1
            motionManager.startDeviceMotionUpdates()
        }

    }

    @IBAction func btnStartPollingTouched(sender: AnyObject) {
        motionManager.startDeviceMotionUpdates()
        timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target:self, selector: Selector("tick"), userInfo: nil, repeats: true)
    }
    
    func tick() {
        let motion = motionManager.deviceMotion
        
        self.lblAcceleration.text = String(format: "Acceleration Z: %.2fGs", motion!.gravity.z)
        self.lblGyro.text = String(format: "Gyro X: %.2fr/s", motion!.rotationRate.x)
    }
    
    @IBAction func btnStopPollingTouched(sender: AnyObject) {
        motionManager.stopDeviceMotionUpdates()
        timer.invalidate()
        timer = nil
    }
    
    @IBAction func btnStartEventsTouched(sender: AnyObject) {
        motionManager.deviceMotionUpdateInterval = 1.0
        motionManager.startDeviceMotionUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {
            motion, error in
            self.lblAcceleration.text = String(format: "Acceleration Z: %.2fGs", motion!.gravity.z)
            self.lblGyro.text = String(format: "Gyro X: %.2fr/s", motion!.rotationRate.x)
        })
    }
    
    @IBAction func btnStopEventsTouched(sender: AnyObject) {
        motionManager.stopDeviceMotionUpdates()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

