<commit_before>//
//  ChargerDetailViewController.swift
//  Spark
//
//  Created by <NAME> on 28/11/15.
//  Copyright © 2015 Zygote Labs. All rights reserved.
//

import UIKit
import MapKit
import Contacts

class ChargerDetailViewController: UIViewController, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, CLLocationManagerDelegate {
    // Outlets
    @IBOutlet var imageThumbnail: UIImageView!
    @IBOutlet var labelTitle: UILabel!
    @IBOutlet var labelSubtitle: UILabel!
    @IBOutlet var labelAccess: UILabel!
    @IBOutlet var labelNumberOfPoints: UILabel!
    @IBOutlet var labelStatus: UILabel!
    @IBOutlet var chargingPointTableView: UITableView!
    @IBOutlet var dataLastUpdateTimeLabel: UILabel!
    @IBOutlet var labelTransportETA: UILabel!
    @IBOutlet var indicatorImageLoader: UIActivityIndicatorView!
    
    // Views
    @IBOutlet var viewNumberOfPoints: UIView!
    @IBOutlet var viewChargerStatus: UIView!
    @IBOutlet var viewHeader: UIView!
    @IBOutlet var viewLastUpdateTime: UIView!
    
    // Location
    var locationManager: CLLocationManager?
    /* We will use this property to keep track on whether
    or not positioning is active */
    var isActive: Bool = false
    
    
    var charger: ChargerPrimary?
    var connections: [Connection] = [Connection]()
    
    var showingLargeImage: Bool?
    var originalThumbnailImageFrame: CGRect?
    
    var totalChargingPointQuantityAvailable: Bool?
    
    var imagePicker: UIImagePickerController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        labelAccess.text = ""
        
        // Formatting the tableView
        let nib = UINib(nibName: "ConnectionTableViewCell", bundle: nil)
        chargingPointTableView.registerNib(nib, forCellReuseIdentifier: "net.zygotelabs.connectioncell")
        chargingPointTableView.tableFooterView = UIView(frame: CGRectZero)
        
        // Download charger thumbnail image
        if let thumbnailImageURL = charger?.chargerImage {
            downloadThumbnailImage(thumbnailImageURL)
            // Add gestureRecognizer if we have loaded an image
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ChargerDetailViewController.toggleFullImage(_:)))
            imageThumbnail.userInteractionEnabled = true
            imageThumbnail.addGestureRecognizer(tapGestureRecognizer)
        } else {
            // Add gestureRecognizer that lets user take and upload photo
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ChargerDetailViewController.grabAndLoadUserPhoto(_:)))
            imageThumbnail.userInteractionEnabled = true
            imageThumbnail.addGestureRecognizer(tapGestureRecognizer)
            
            if let image = UIImage(named: "PlaceholderImageIcon") {
                imageThumbnail.image = image
            }
        }
        
        // Check location permission and start location update.
        if checkLocationAuthorization(){
            locationManager?.desiredAccuracy = 50
            locationManager?.distanceFilter = 50
            locationManager?.startUpdatingLocation()
            isActive = true
        }
    }
    
    func checkLocationAuthorization() -> Bool{
        let authStatus = CLLocationManager.authorizationStatus()
        
        switch authStatus {
        case CLAuthorizationStatus.AuthorizedWhenInUse:
            // Permission already granted
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            return true
            
        default:
            // Permission not granted.
            return false
            
        }
    }
    
    func generateNavigationButton() -> UIBarButtonItem {
        // Button that lets user navigate to charger address.
        let navigationButtonItem = UIBarButtonItem(title: "Navigate", style: .Plain, target: self, action: #selector(ChargerDetailViewController.navigateButtonTapped))
        navigationButtonItem.image = UIImage(named: "CarIcon")
        
        return navigationButtonItem
        
    }
    
    func generateCallButton() -> UIBarButtonItem {
        // Button that lets user call the number associated wtih the charging station.
        let callButtonItem = UIBarButtonItem(title: "Call", style: .Plain, target: self, action: #selector(ChargerDetailViewController.callButtonTapped))
        callButtonItem.image = UIImage(named: "CallIcon")
        
        return callButtonItem
    }
    
    func navigateButtonTapped() {
        let addressDictionary = [String(CNPostalAddressStreetKey): labelSubtitle.text as! AnyObject]
        let chargingPointPlaceCoordinate = CLLocationCoordinate2D(latitude: (charger?.chargerLatitude)!, longitude: (charger?.chargerLongitude)!)
        let placemark = MKPlacemark(coordinate: chargingPointPlaceCoordinate, addressDictionary: addressDictionary)
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = labelSubtitle.text
        
        
        let options = [MKLaunchOptionsDirectionsModeKey:
            MKLaunchOptionsDirectionsModeDriving]
        
        mapItem.openInMapsWithLaunchOptions(options)
    }
    
    func callButtonTapped() {
        let phoneNumber = charger?.chargerDetails?.chargerPrimaryContactNumber?.stringByReplacingOccurrencesOfString(" ", withString: "")
        
        if let callUrl = NSURL(string: "tel:\(phoneNumber!)") {
            UIApplication.sharedApplication().openURL(callUrl)
        }
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        manipulateThumbnailImage()
        setChargerInfoToOutlets()
        
        addViewAppearanceElements()
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        showingLargeImage = false
        originalThumbnailImageFrame = imageThumbnail.frame
    }
    
    @IBAction func animateDateView() {
        UIView.animateWithDuration(0.5, animations: {
            if (self.viewLastUpdateTime.alpha > 0){
                self.viewLastUpdateTime.alpha = 0.0
            }else {
                self.viewLastUpdateTime.alpha = 1.0
            }
        })
    }
    
    func addViewAppearanceElements(){
        viewNumberOfPoints.layer.borderWidth = 0.25
        viewNumberOfPoints.layer.borderColor = UIColor.whiteColor().CGColor
        viewChargerStatus.layer.borderWidth = 0.25
        viewChargerStatus.layer.borderColor = UIColor.whiteColor().CGColor
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors =  [
            UIColor(red: 93, green: 116, blue: 177, alpha: 1),
            UIColor(red: 92, green: 108, blue: 171, alpha: 1)
        ]
        
        gradientLayer.frame = viewNumberOfPoints.bounds
        self.viewNumberOfPoints.layer.addSublayer(gradientLayer)
    }
    
    func grabAndLoadUserPhoto(img: AnyObject)
    {
        imagePicker =  UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = .Camera
        presentViewController(imagePicker, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        imageThumbnail.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        
        // Ask user for confirmation before uploading photo.
        //Action
        let photoUploadAction = UIAlertAction(title: "Yes", style: .Default) { (alert: UIAlertAction!) -> Void in
            // User confirmed. Post the photo
            let userPhotoSubmissionManager = UserPhotoSubmissionManager()
            if let chargerId = self.charger?.chargerId{
                userPhotoSubmissionManager.myImageUploadRequest(self.imageThumbnail, chargerId: chargerId)
                self.showPhotoSubmissionConfirmationAlert()
            }
        }<commit_msg>Added ability to let the user choose between the camera and the photo library.<commit_after>//
//  ChargerDetailViewController.swift
//  Spark
//
//  Created by <NAME> on 28/11/15.
//  Copyright © 2015 Zygote Labs. All rights reserved.
//

import UIKit
import MapKit
import Contacts

class ChargerDetailViewController: UIViewController, UITableViewDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate, CLLocationManagerDelegate {
    // Outlets
    @IBOutlet var imageThumbnail: UIImageView!
    @IBOutlet var labelTitle: UILabel!
    @IBOutlet var labelSubtitle: UILabel!
    @IBOutlet var labelAccess: UILabel!
    @IBOutlet var labelNumberOfPoints: UILabel!
    @IBOutlet var labelStatus: UILabel!
    @IBOutlet var chargingPointTableView: UITableView!
    @IBOutlet var dataLastUpdateTimeLabel: UILabel!
    @IBOutlet var labelTransportETA: UILabel!
    @IBOutlet var indicatorImageLoader: UIActivityIndicatorView!
    
    // Views
    @IBOutlet var viewNumberOfPoints: UIView!
    @IBOutlet var viewChargerStatus: UIView!
    @IBOutlet var viewHeader: UIView!
    @IBOutlet var viewLastUpdateTime: UIView!
    
    // Location
    var locationManager: CLLocationManager?
    /* We will use this property to keep track on whether
    or not positioning is active */
    var isActive: Bool = false
    
    
    var charger: ChargerPrimary?
    var connections: [Connection] = [Connection]()
    
    var showingLargeImage: Bool?
    var originalThumbnailImageFrame: CGRect?
    
    var totalChargingPointQuantityAvailable: Bool?
    
    var imagePicker: UIImagePickerController!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        labelAccess.text = ""
        
        // Formatting the tableView
        let nib = UINib(nibName: "ConnectionTableViewCell", bundle: nil)
        chargingPointTableView.registerNib(nib, forCellReuseIdentifier: "net.zygotelabs.connectioncell")
        chargingPointTableView.tableFooterView = UIView(frame: CGRectZero)
        
        // Download charger thumbnail image
        if let thumbnailImageURL = charger?.chargerImage {
            downloadThumbnailImage(thumbnailImageURL)
            // Add gestureRecognizer if we have loaded an image
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ChargerDetailViewController.toggleFullImage(_:)))
            imageThumbnail.userInteractionEnabled = true
            imageThumbnail.addGestureRecognizer(tapGestureRecognizer)
        } else {
            // Add gestureRecognizer that lets user take and upload photo
            let tapGestureRecognizer = UITapGestureRecognizer(target: self, action:#selector(ChargerDetailViewController.grabAndLoadUserPhoto(_:)))
            imageThumbnail.userInteractionEnabled = true
            imageThumbnail.addGestureRecognizer(tapGestureRecognizer)
            
            if let image = UIImage(named: "PlaceholderImageIcon") {
                imageThumbnail.image = image
            }
        }
        
        // Check location permission and start location update.
        if checkLocationAuthorization(){
            locationManager?.desiredAccuracy = 50
            locationManager?.distanceFilter = 50
            locationManager?.startUpdatingLocation()
            isActive = true
        }
    }
    
    func checkLocationAuthorization() -> Bool{
        let authStatus = CLLocationManager.authorizationStatus()
        
        switch authStatus {
        case CLAuthorizationStatus.AuthorizedWhenInUse:
            // Permission already granted
            locationManager = CLLocationManager()
            locationManager?.delegate = self
            return true
            
        default:
            // Permission not granted.
            return false
            
        }
    }
    
    func generateNavigationButton() -> UIBarButtonItem {
        // Button that lets user navigate to charger address.
        let navigationButtonItem = UIBarButtonItem(title: "Navigate", style: .Plain, target: self, action: #selector(ChargerDetailViewController.navigateButtonTapped))
        navigationButtonItem.image = UIImage(named: "CarIcon")
        
        return navigationButtonItem
        
    }
    
    func generateCallButton() -> UIBarButtonItem {
        // Button that lets user call the number associated wtih the charging station.
        let callButtonItem = UIBarButtonItem(title: "Call", style: .Plain, target: self, action: #selector(ChargerDetailViewController.callButtonTapped))
        callButtonItem.image = UIImage(named: "CallIcon")
        
        return callButtonItem
    }
    
    func navigateButtonTapped() {
        let addressDictionary = [String(CNPostalAddressStreetKey): labelSubtitle.text as! AnyObject]
        let chargingPointPlaceCoordinate = CLLocationCoordinate2D(latitude: (charger?.chargerLatitude)!, longitude: (charger?.chargerLongitude)!)
        let placemark = MKPlacemark(coordinate: chargingPointPlaceCoordinate, addressDictionary: addressDictionary)
        let mapItem = MKMapItem(placemark: placemark)
        mapItem.name = labelSubtitle.text
        
        
        let options = [MKLaunchOptionsDirectionsModeKey:
            MKLaunchOptionsDirectionsModeDriving]
        
        mapItem.openInMapsWithLaunchOptions(options)
    }
    
    func callButtonTapped() {
        let phoneNumber = charger?.chargerDetails?.chargerPrimaryContactNumber?.stringByReplacingOccurrencesOfString(" ", withString: "")
        
        if let callUrl = NSURL(string: "tel:\(phoneNumber!)") {
            UIApplication.sharedApplication().openURL(callUrl)
        }
    }
    
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        manipulateThumbnailImage()
        setChargerInfoToOutlets()
        
        addViewAppearanceElements()
        
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        showingLargeImage = false
        originalThumbnailImageFrame = imageThumbnail.frame
    }
    
    @IBAction func animateDateView() {
        UIView.animateWithDuration(0.5, animations: {
            if (self.viewLastUpdateTime.alpha > 0){
                self.viewLastUpdateTime.alpha = 0.0
            }else {
                self.viewLastUpdateTime.alpha = 1.0
            }
        })
    }
    
    func addViewAppearanceElements(){
        viewNumberOfPoints.layer.borderWidth = 0.25
        viewNumberOfPoints.layer.borderColor = UIColor.whiteColor().CGColor
        viewChargerStatus.layer.borderWidth = 0.25
        viewChargerStatus.layer.borderColor = UIColor.whiteColor().CGColor
        
        let gradientLayer = CAGradientLayer()
        gradientLayer.colors =  [
            UIColor(red: 93, green: 116, blue: 177, alpha: 1),
            UIColor(red: 92, green: 108, blue: 171, alpha: 1)
        ]
        
        gradientLayer.frame = viewNumberOfPoints.bounds
        self.viewNumberOfPoints.layer.addSublayer(gradientLayer)
    }
    
    func grabAndLoadUserPhoto(img: AnyObject)
    {
        /* Define a UIImagePickerController that lets the user 
           supply a photo of a charging station */
        
        imagePicker =  UIImagePickerController()
        imagePicker.delegate = self
        
        //Camera Source Action
        let cameraSourceAction = UIAlertAction(title: "Take a Photo", style: .Default) { (alert: UIAlertAction!) -> Void in
            self.imagePicker.sourceType = .Camera
            self.presentViewController(self.imagePicker, animated: true, completion: nil)
        }
        
        //Album Source Action
        let albumSourceAction = UIAlertAction(title: "Photo Library", style: .Default) { (alert: UIAlertAction!) -> Void in
            self.imagePicker.sourceType = .PhotoLibrary
            self.presentViewController(self.imagePicker, animated: true, completion: nil)
        }
        
        // Ask user whether to grab photo from the camera or the photo album.
        let photoSourcePromptAlert = UIAlertController(title: "Photo Submission", message: "Submit a photo for this charging station", preferredStyle: UIAlertControllerStyle.ActionSheet)
        photoSourcePromptAlert.addAction(cameraSourceAction)
        photoSourcePromptAlert.addAction(albumSourceAction)
        self.presentViewController(photoSourcePromptAlert, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        imagePicker.dismissViewControllerAnimated(true, completion: nil)
        imageThumbnail.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        
        // Ask user for confirmation before uploading photo.
        //Action
        let photoUploadAction = UIAlertAction(title: "Yes", style: .Default) { (alert: UIAlertAction!) -> Void in
            // User confirmed. Post the photo
            let userPhotoSubmissionManager = UserPhotoSubmissionManager()
            if let chargerId = self.charger?.chargerId{
                userPhotoSubmissionManager.myImageUploadRequest(self.imageThumbnail, chargerId: chargerId)
                self.showPhotoSubmissionConfirmationAlert()
            }
        }
{'fraction_non_alphanumeric': 0.07324510932105868, 'fraction_numerical': 0.005293440736478711, 'mean_word_length': 2.6761844331641287, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3859350', 'n_tokens_mistral': 4737, 'n_tokens_neox': 4528, 'n_words': 1024}