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

import UIKit
import CoreMotion

class ViewController: UIViewController {

    var motionManager: CMMotionManager!

    var xAcceleration: Double!
    var yAcceleration: Double!
    var xPosition: Double!
    var yPosition: Double!
    var circle: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = UIColor.whiteColor()
        
        let fileName: String = "circle_blue.png"
        let image: UIImage = UIImage(named: fileName)!
        let size: CGSize = image.size
        let rect: CGRect = CGRect(origin: CGPointZero, size: size)
        circle = UIImageView(frame: rect)
        circle.image = image
        
        xAcceleration = 0.0
        yAcceleration = 0.0
        xPosition = 0.0
        yPosition = 0.0
        
        // Center the image
        circle.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds))
        self.view.addSubview(circle)
        
        motionManager = CMMotionManager()
        motionManager.accelerometerUpdateInterval = 0.2
        motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: {
            data, error in
                self.handleAccelertionData(data!.acceleration)
        })
    }

    func SIGN (x: Double) -> Double {
        if (x < 0.0) {
            return -1.0
        }
        else {
            return 1.0
        }
    }
    
    func handleAccelertionData(data: CMAcceleration) {
        let xCurrentAccel: Double = -data.x
        let yCurrentAccel: Double = data.y
        
        let accelDirX: Double = SIGN(xPosition) * -1.0
        let newDirX: Double = SIGN(xCurrentAccel)
        let accelDirY: Double = SIGN(yPosition) * -1.0
        let newDirY: Double = SIGN(yCurrentAccel)
        
        if (accelDirX == newDirX) {
            xAcceleration = (abs(xAcceleration) + 1.00) * SIGN(xAcceleration)
        }
        if (accelDirY == newDirY) {
            yAcceleration = (abs(yAcceleration) + 1.00) * SIGN(yAcceleration)
        }
        
        xPosition = -xAcceleration * xCurrentAccel
        yPosition = -yAcceleration * yCurrentAccel
        
        let rect: CGRect = CGRectOffset(circle.frame, CGFloat(xPosition), CGFloat(yPosition))
        if (CGRectContainsRect(self.view.bounds, rect)) {
            circle.frame = rect
        }
    }
    
    func isLandscape() -> Bool {
        return UIDeviceOrientationIsLandscape(UIDevice.currentDevice().orientation)
    }
    
    func isPortrait() -> Bool {
        return UIDeviceOrientationIsPortrait(UIDevice.currentDevice().orientation)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

