//
//  ViewController.swift
//  Gyroscope
//
//  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 lblRotationX: UILabel!
    @IBOutlet weak var lblRotationY: UILabel!
    @IBOutlet weak var lblRotationZ: UILabel!
    @IBOutlet weak var lblMaxRotationX: UILabel!
    @IBOutlet weak var lblMaxRotationY: UILabel!
    @IBOutlet weak var lblMaxRotationZ: UILabel!

    var motionManager: CMMotionManager!
    var maxRotationX: Double!
    var maxRotationY: Double!
    var maxRotationZ: Double!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        maxRotationX = 0
        maxRotationY = 0
        maxRotationZ = 0
        
        motionManager = CMMotionManager()
        motionManager.gyroUpdateInterval = 0.1
    }

    @IBAction func btnStartTouched(sender: AnyObject) {
        motionManager.startGyroUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {
            gyroData, error in
            self.outputRotationData(gyroData!.rotationRate)
        })
    }

    func outputRotationData(rotation: CMRotationRate) {
        lblRotationX.text = String(format:"Rotation X: %.2fr/s",rotation.x)
        if fabs(rotation.x) > fabs(maxRotationX) {
            maxRotationX = rotation.x;
            lblMaxRotationX.text = String(format:"Max Rotation X: %.2f", maxRotationX)
        }
        lblRotationY.text = String(format:"Rotation Y: %.2fr/s",rotation.y)
        if fabs(rotation.y) > fabs(maxRotationY) {
            maxRotationY = rotation.y;
            lblMaxRotationY.text = String(format:"Max Rotation Y: %.2f", maxRotationY)
        }
        lblRotationZ.text = String(format:"Rotation Z: %.2fr/s",rotation.z)
        if fabs(rotation.z) > fabs(maxRotationZ) {
            maxRotationZ = rotation.z;
            lblMaxRotationZ.text = String(format:"Max Rotation Z: %.2f", maxRotationZ)
        }
    }

    @IBAction func btnStopTouched(sender: AnyObject) {
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

