<commit_before>//
//  EditRestaurantViewController.swift
//  FriendlyEats
//
//  Created by <NAME> on 2/5/18.
//  Copyright © 2018 Firebase. All rights reserved.
//

import UIKit
import Firebase
import FirebaseStorage

class EditRestaurantViewController: UIViewController, UINavigationControllerDelegate {

    // MARK: Properties
    
    var restaurant: Restaurant?
    var imagePicker = UIImagePickerController()
    var downloadUrl: String?
    
    
    // MARK: Outlets
    
    @IBOutlet weak var restaurantImageView: UIImageView!
    @IBOutlet weak var restaurantNameTextField: UITextField!
    @IBOutlet weak var locationTextField: UITextField!
    @IBOutlet weak var cuisineTextField: UITextField!
    @IBOutlet weak var priceTextField: UITextField!
    
    static func fromStoryboard(_ storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)) -> EditRestaurantViewController {
        let controller = storyboard.instantiateViewController(withIdentifier: "EditRestaurantViewController") as! EditRestaurantViewController
        return controller
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        hideKeyboardWhenTappedAround()
        if let _ = restaurant {
            populateRestaurant()
        }
        //imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
    }

    // populate restaurant with current data
    func populateRestaurant() {
        restaurantNameTextField.text = restaurant?.name
        locationTextField.text = restaurant?.city
        cuisineTextField.text = restaurant?.category
        priceTextField.text = restaurant?.price.description
        restaurantImageView.sd_setImage(with: restaurant?.photoURL)
    }
    
    func saveChanges() {
        var data = [
            "name": restaurantNameTextField.text,
            "city": locationTextField.text,
            "category": cuisineTextField.text,
            "price": Int(priceTextField.text!)
            //"photoURL": dostuffhere
            ] as [String : Any]
        // if photo was changed, add the new url
        if let downloadUrl = downloadUrl {
            data["photoURL"] = downloadUrl
        }
        Firestore.firestore().collection("restaurants").document((restaurant?.documentID)!).updateData(data){ err in
            if let err = err {
                print("Error writing document: \(err)")
            } else {
                self.didSaveAlert()
            }
        }
    }
    
    // MARK: Alert Messages
    
    func didSaveAlert() {
        var message = "Successfully saved!"
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { action in
            self.navigationController?.popViewController(animated: true)
        }
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func willSaveAlert() {
        var message = "Are you sure you want to save changes to this restaurant?"
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        let saveAction = UIAlertAction(title: "Save", style: .default) { action in
            self.saveChanges()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)

        self.present(alertController, animated: true, completion: nil)
    }
    
    // If data in text fields isn't valid, give an alert
    func invalidDataAlert(message: String) {
        var title = "Invalid Input"
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func saveImage(photoData: Data) {
        Storage.storage().reference(withPath: (restaurant?.documentID)!).putData(photoData, metadata: nil) { (metadata, error) in
            if let error = error {
                print(error)
            }
            guard let metadata = metadata else {
                return
            }
            self.downloadUrl = metadata.downloadURL()?.absoluteString
        }
        
    }
    
    @objc func inputToolbarDonePressed() {
        resignFirstResponder()
    }
    
    @objc func keyboardNextButton() {
        if locationTextField.isFirstResponder {
            cuisineTextField.becomeFirstResponder()
        } else if cuisineTextField.isFirstResponder {
            priceTextField.becomeFirstResponder()
        } else if restaurantNameTextField.isFirstResponder {
           locationTextField.becomeFirstResponder()
        } else {
            resignFirstResponder()
        }
    }
    
    @objc func keyboardPreviousButton() {
        if locationTextField.isFirstResponder {
            restaurantNameTextField.becomeFirstResponder()
        } else if cuisineTextField.isFirstResponder {
            locationTextField.becomeFirstResponder()
        } else if priceTextField.isFirstResponder {
            cuisineTextField.becomeFirstResponder()
        } else {
            resignFirstResponder()
        }
    }
    
    lazy var inputToolbar: UIToolbar = {
        var toolbar = UIToolbar()
        toolbar.barStyle = .default
        toolbar.isTranslucent = true
        toolbar.sizeToFit()
        
        var doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.inputToolbarDonePressed))
        var flexibleSpaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        var fixedSpaceButton = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        
        var nextButton  = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_keyboard_arrow_left"), style: .plain, target: self, action: #selector(self.keyboardPreviousButton))
        nextButton.width = 50.0
        var previousButton  = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_keyboard_arrow_right"), style: .plain, target: self, action: #selector(self.keyboardNextButton))
        
        toolbar.setItems([fixedSpaceButton, nextButton, fixedSpaceButton, previousButton, flexibleSpaceButton, doneButton], animated: false)
        toolbar.isUserInteractionEnabled = true
        
        return toolbar
    }()
    
    @IBAction func selectNewImage(_ sender: Any) {
        selectImage()
    }<commit_msg>not sure what changed here<commit_after>//
//  EditRestaurantViewController.swift
//  FriendlyEats
//
//  Created by <NAME> on 2/5/18.
//  Copyright © 2018 Firebase. All rights reserved.
//

import UIKit
import Firebase
import FirebaseStorage

class EditRestaurantViewController: UIViewController, UINavigationControllerDelegate {

    // MARK: Properties
    
    var restaurant: Restaurant?
    var imagePicker = UIImagePickerController()
    var downloadUrl: String?
    
    
    // MARK: Outlets
    
    @IBOutlet weak var restaurantImageView: UIImageView!
    @IBOutlet weak var restaurantNameTextField: UITextField!
    @IBOutlet weak var locationTextField: UITextField!
    @IBOutlet weak var cuisineTextField: UITextField!
    @IBOutlet weak var priceTextField: UITextField!
    
    static func fromStoryboard(_ storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)) -> EditRestaurantViewController {
        let controller = storyboard.instantiateViewController(withIdentifier: "EditRestaurantViewController") as! EditRestaurantViewController
        return controller
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        hideKeyboardWhenTappedAround()
        if let _ = restaurant {
            populateRestaurant()
        }
        //imagePicker.delegate = self as? UIImagePickerControllerDelegate & UINavigationControllerDelegate
    }

    // populate restaurant with current data
    func populateRestaurant() {
        restaurantNameTextField.text = restaurant?.name
        locationTextField.text = restaurant?.city
        cuisineTextField.text = restaurant?.category
        priceTextField.text = restaurant?.price.description
        restaurantImageView.sd_setImage(with: restaurant?.photoURL)
    }
    
    func saveChanges() {
        var data = [
            "name": restaurantNameTextField.text,
            "city": locationTextField.text,
            "category": cuisineTextField.text,
            "price": Int(priceTextField.text!)
            ] as [String : Any]
        // if photo was changed, add the new url
        if let downloadUrl = downloadUrl {
            data["photoURL"] = downloadUrl
        }
        Firestore.firestore().collection("restaurants").document((restaurant?.documentID)!).updateData(data){ err in
            if let err = err {
                print("Error writing document: \(err)")
            } else {
                self.didSaveAlert()
            }
        }
    }
    
    // MARK: Alert Messages
    
    func didSaveAlert() {
        var message = "Successfully saved!"
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "OK", style: .default) { action in
            self.navigationController?.popViewController(animated: true)
        }
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func willSaveAlert() {
        let message = "Are you sure you want to save changes to this restaurant?"
        let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        let saveAction = UIAlertAction(title: "Save", style: .default) { action in
            self.saveChanges()
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
        alertController.addAction(saveAction)
        alertController.addAction(cancelAction)

        self.present(alertController, animated: true, completion: nil)
    }
    
    // If data in text fields isn't valid, give an alert
    func invalidDataAlert(message: String) {
        let title = "Invalid Input"
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
        alertController.addAction(okAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func saveImage(photoData: Data) {
        Storage.storage().reference(withPath: (restaurant?.documentID)!).putData(photoData, metadata: nil) { (metadata, error) in
            if let error = error {
                print(error)
            }
            guard let metadata = metadata else {
                return
            }
            self.downloadUrl = metadata.downloadURL()?.absoluteString
        }
        
    }
    
    // MARK: Keyboard functionality
    
    @objc func inputToolbarDonePressed() {
        resignFirstResponder()
    }
    
    @objc func keyboardNextButton() {
        if locationTextField.isFirstResponder {
            cuisineTextField.becomeFirstResponder()
        } else if cuisineTextField.isFirstResponder {
            priceTextField.becomeFirstResponder()
        } else if restaurantNameTextField.isFirstResponder {
           locationTextField.becomeFirstResponder()
        } else {
            resignFirstResponder()
        }
    }
    
    @objc func keyboardPreviousButton() {
        if locationTextField.isFirstResponder {
            restaurantNameTextField.becomeFirstResponder()
        } else if cuisineTextField.isFirstResponder {
            locationTextField.becomeFirstResponder()
        } else if priceTextField.isFirstResponder {
            cuisineTextField.becomeFirstResponder()
        } else {
            resignFirstResponder()
        }
    }
    
    lazy var inputToolbar: UIToolbar = {
        var toolbar = UIToolbar()
        toolbar.barStyle = .default
        toolbar.isTranslucent = true
        toolbar.sizeToFit()
        
        var doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(self.inputToolbarDonePressed))
        var flexibleSpaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        var fixedSpaceButton = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        
        var nextButton  = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_keyboard_arrow_left"), style: .plain, target: self, action: #selector(self.keyboardPreviousButton))
        nextButton.width = 50.0
        var previousButton  = UIBarButtonItem(image: #imageLiteral(resourceName: "ic_keyboard_arrow_right"), style: .plain, target: self, action: #selector(self.keyboardNextButton))
        
        toolbar.setItems([fixedSpaceButton, nextButton, fixedSpaceButton, previousButton, flexibleSpaceButton, doneButton], animated: false)
        toolbar.isUserInteractionEnabled = true
        
        return toolbar
    }()
    
    // MARK: IBActions
    
    @IBAction func selectNewImage(_ sender: Any) {
        selectImage()
    }
{'fraction_non_alphanumeric': 0.08655136424630983, 'fraction_numerical': 0.0016400775309378262, 'mean_word_length': 2.651333696243876, 'pattern_counts': {'":': 9, '<': 5, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4618700', 'n_tokens_mistral': 3570, 'n_tokens_neox': 3432, 'n_words': 835}