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

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var imgArrow: UIImageView!
    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        imgArrow = UIImageView(image: UIImage(named: "arrow.png"))
        self.view.addSubview(imgArrow)
        
        if (!CLLocationManager.locationServicesEnabled()) {
            return
        }
        
        locationManager = CLLocationManager()
        locationManager.delegate = self
        
        if (CLLocationManager.headingAvailable()) {
            locationManager.startUpdatingHeading()
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        imgArrow.center = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds))
    }
    
    func locationManagerShouldDisplayHeadingCalibration(manager: CLLocationManager) -> Bool {
        return true
    }

    func locationManager(manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
        let heading:CGFloat = CGFloat(-M_PI * (newHeading.magneticHeading + 90) / 180.0)
        imgArrow.transform = CGAffineTransformMakeRotation(heading)

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


}

