Advertisement
Guest User

Untitled

a guest
Mar 21st, 2017
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 13.71 KB | None | 0 0
  1. //
  2. //  StartHarvestingTableViewController.swift
  3. //  Sproyteappen
  4. //
  5. //  Created by Emil Ramsdal on 13/03/2017.
  6. //  Copyright © 2017 Veslebråten Data AS. All rights reserved.
  7. //
  8.  
  9. import UIKit
  10. import FirebaseDatabase
  11. import CoreLocation
  12.  
  13. class StartHarvestingTableViewController: UITableViewController, UIPickerViewDelegate, UIPickerViewDataSource, CLLocationManagerDelegate {
  14.  
  15.  
  16.     var fieldList: [Field] = []
  17.     var cropTypes: [CropType] = []
  18.     var harvestingList: [Harvesting] = []
  19.     var pesticideList: [Pesticide] = []
  20.     var pesticideWorkList: [PesticideWork] = []
  21.    
  22.     var selectedField: Field?
  23.     var currentHarvestingWorkKey: String = ""
  24.     var processingDays: Int?
  25.    
  26.     var hasAddedFields: Bool = false
  27.    
  28.    
  29.     var locationManager: CLLocationManager = CLLocationManager()
  30.     var startLocation: CLLocation!
  31.    
  32.    
  33.     @IBOutlet weak var fieldNameLabel: UILabel!
  34.     @IBOutlet weak var fieldPicker: UIPickerView!
  35.     @IBOutlet weak var timeLabel: UILabel!
  36.     @IBOutlet weak var startHarvestingButton: UIButton!
  37.     @IBOutlet weak var infoLabel: UILabel!
  38.    
  39.    
  40.     override func viewDidLoad() {
  41.         super.viewDidLoad()
  42.        
  43.         locationManager.desiredAccuracy = kCLLocationAccuracyBest
  44.         locationManager.delegate = self
  45.         locationManager.requestWhenInUseAuthorization()
  46.         locationManager.startUpdatingLocation()
  47.        
  48.         fieldPicker.dataSource = self
  49.         fieldPicker.delegate = self
  50.        
  51.         tableView.allowsMultipleSelectionDuringEditing = false
  52.         timeLabel.text = TimeMethods.getTimeNow()
  53.        
  54.        
  55.         harvestingRef?.queryOrdered(byChild: "fieldKey").observeSingleEvent(of: .value, with: { snapshot in
  56.             var newItems: [Harvesting] = []
  57.            
  58.             for item in snapshot.children {
  59.                 let harvesting = Harvesting(snapshot: item as! FIRDataSnapshot)
  60.                 newItems.append(harvesting)
  61.  
  62.             }
  63.            
  64.             self.harvestingList = newItems
  65.             self.tableView.reloadData()
  66.            
  67.            
  68.             cropTypeRef.queryOrdered(byChild: "name").observeSingleEvent(of: .value, with: { snapshot in
  69.                 var newItems: [CropType] = []
  70.                 for item in snapshot.children {
  71.                     let cropType = CropType(snapshot: item as! FIRDataSnapshot)
  72.                     if(cropType.active){
  73.                         newItems.append(cropType)
  74.                     }
  75.                 }
  76.                 self.cropTypes = newItems
  77.                 self.tableView.reloadData()
  78.                
  79.                
  80.                
  81.                 fieldRef.queryOrdered(byChild: "name").observeSingleEvent(of :.value, with: { snapshot in
  82.                     var newItems: [Field] = []
  83.                    
  84.                     for item in snapshot.children {
  85.                         let field = Field(snapshot: item as! FIRDataSnapshot)
  86.                         self.hasAddedFields = true
  87.                         if(!field.hidden && self.checkIfFieldIsAvailable(field: field)){
  88.                             newItems.append(field)
  89.                         }
  90.                        
  91.                     }
  92.                    
  93.                     self.fieldList = newItems
  94.                     self.fieldPicker.reloadAllComponents()
  95.                     self.tableView.reloadData()
  96.                    
  97.                     if(self.fieldList.count > 0){
  98.                         self.fieldNameLabel.text = self.fieldList[0].name + " - " + self.fieldList[0].crop
  99.                         self.selectedField = self.fieldList[0]
  100.                     }
  101.                     else {
  102.                         if(self.hasAddedFields){
  103.                             self.fieldNameLabel.text = "All fields harvested"
  104.                         } else {
  105.                             self.fieldNameLabel.text = "You need to add fields"
  106.                         }
  107.                        
  108.                     }
  109.                    
  110.                     self.fieldPickerUpdateField(number: 0)
  111.                    
  112.                     pesticideWorkRef?.queryOrdered(byChild: "timeFinished").observeSingleEvent(of: .value, with: { snapshot in
  113.                         var newItems: [PesticideWork] = []
  114.                        
  115.                         for item in snapshot.children {
  116.                            
  117.                             let pesticideWork = PesticideWork(snapshot: item as! FIRDataSnapshot)
  118.                            
  119.                             if(pesticideWork.finished){
  120.                                 newItems.append(pesticideWork)
  121.                             }
  122.                            
  123.                         }
  124.                        
  125.                         self.pesticideWorkList = newItems
  126.                         self.tableView.reloadData()
  127.                        
  128.                         let pesticideForCurrentFieldRef: FIRDatabaseReference
  129.                        
  130.                         if(self.selectedField?.ecologic)!{
  131.                             pesticideForCurrentFieldRef = (ecologicPesticideRef.child((self.selectedField?.crop)!))
  132.                         } else {
  133.                             pesticideForCurrentFieldRef = (normalPesticideRef.child((self.selectedField?.crop)!))
  134.                         }
  135.                        
  136.  
  137.                         pesticideForCurrentFieldRef.queryOrdered(byChild: "name").observeSingleEvent(of: .value, with: { snapshot in
  138.                             var newItems: [Pesticide] = []
  139.                            
  140.                             for item in snapshot.children {
  141.                                 let pesticide = Pesticide(snapshot: item as! FIRDataSnapshot)
  142.                                
  143.                                 newItems.append(pesticide)
  144.  
  145.                             }
  146.                            
  147.                             self.pesticideList = newItems
  148.                             self.fieldPickerUpdateField(number: 0)
  149.                             self.selectedField = self.fieldList[0]
  150.                             self.updateInfoLabel(field: self.fieldList[0])
  151.                             self.tableView.reloadData()
  152.  
  153.                         })
  154.                        
  155.  
  156.                     })
  157.                    
  158.                    
  159.                 })
  160.                
  161.  
  162.             })
  163.            
  164.            
  165.             self.fieldPicker.reloadAllComponents()
  166.            
  167.         })
  168.  
  169.     }
  170.    
  171.     func downloadPesticideList(field: Field){
  172.        
  173.         let pesticideForCurrentFieldRef: FIRDatabaseReference
  174.        
  175.         if(field.ecologic){
  176.             pesticideForCurrentFieldRef = (ecologicPesticideRef.child(field.crop))
  177.         } else {
  178.             pesticideForCurrentFieldRef = (normalPesticideRef.child(field.crop))
  179.         }
  180.        
  181.        
  182.  
  183.         pesticideForCurrentFieldRef.queryOrdered(byChild: "name").observeSingleEvent(of: .value, with: { snapshot in
  184.             var newItems: [Pesticide] = []
  185.            
  186.             for item in snapshot.children {
  187.                 let pesticide = Pesticide(snapshot: item as! FIRDataSnapshot)
  188.                
  189.                 newItems.append(pesticide)
  190.                
  191.             }
  192.            
  193.             self.pesticideList.removeAll()
  194.             self.pesticideList = newItems
  195.             self.updateInfoLabel(field: field)
  196.            
  197.             self.tableView.reloadData()
  198.             self.fieldPickerUpdateField(number: 0)
  199.         })
  200.     }
  201.    
  202.    
  203.     func printAllLists(){
  204.         print("fieldList - " + String(describing: fieldList.count))
  205.         print("cropTypes - " + String(describing: cropTypes.count))
  206.         print("harvestingList - " + String(describing: harvestingList.count))
  207.         print("pesticideList - " + String(describing: pesticideList.count))
  208.         print("pesticideWorkList - " + String(describing: pesticideWorkList.count))
  209.     }
  210.    
  211.     func checkIfFieldIsAvailable(field: Field) -> Bool{
  212.        
  213.        
  214.         for item in harvestingList {
  215.             if (item.fieldKey == field.key){
  216.                 for crop in cropTypes{
  217.                     if(crop.name == field.crop){
  218.                         if(crop.multipleHarvesting){
  219.                             return true
  220.                         } else {
  221.                             return false
  222.                         }
  223.                     }
  224.                 }
  225.             }
  226.         }
  227.         return true
  228.     }
  229.    
  230.    
  231.     override func viewDidDisappear(_ animated: Bool) {
  232.         locationManager.stopUpdatingLocation()
  233.     }
  234.    
  235.     override func viewDidAppear(_ animated: Bool) {
  236.         fieldPickerUpdateField(number: 0)
  237.     }
  238.     @IBAction func startHarvestingButton(_ sender: Any) {
  239.        
  240.         guard let field = selectedField else {
  241.             return
  242.         }
  243.         var longitude: CLLocationDegrees = CLLocationDegrees()
  244.         var latitude: CLLocationDegrees = CLLocationDegrees()
  245.         if let startLocation = startLocation{
  246.             longitude = startLocation.coordinate.longitude
  247.             latitude = startLocation.coordinate.latitude
  248.            
  249.            
  250.         }
  251.        
  252.         let longitude1: String = String(describing: longitude)
  253.         let latitude1: String = String(describing: latitude)
  254.        
  255.         let harvesting = Harvesting(timeStart: "", timeFinished: "", fieldKey: field.key, fieldName: field.name, finished: false, longitude: longitude1, latitude: latitude1)
  256.        
  257.         let newHarvestingRef = harvestingRef?.childByAutoId()
  258.        
  259.         newHarvestingRef?.setValue(harvesting.toAnyObject()){ err, ref in
  260.             print(err ?? "Harvesting ok")
  261.        
  262.         }
  263.        
  264.         goToMainHarvestingViewController(key: newHarvestingRef!.key)
  265.     }
  266.    
  267.     func goToMainHarvestingViewController(key: String) {
  268.         let a = self.navigationController?.viewControllers[1] as! MainHarvestingViewController
  269.         a.harvestingKey = key
  270.         let _ = self.navigationController?.popToViewController(a, animated: false)
  271.        
  272.        
  273.     }
  274.    
  275.    
  276.    
  277.  
  278.     func checkIfButtonCanBeEnabled() {
  279.         if(fieldNameLabel.text != ""){
  280.             startHarvestingButton.isEnabled = true
  281.         } else {
  282.             startHarvestingButton.isEnabled = false
  283.         }
  284.     }
  285.    
  286.    
  287.    
  288.    
  289. //    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  290. //
  291. //
  292. //
  293. //        
  294. //    }
  295.    
  296.     func checkProcessingDeadline(field: Field) -> Int {
  297.         var days = 0
  298.  
  299.         for pesticideWork in pesticideWorkList {
  300.             if(pesticideWork.fieldKey == field.key){
  301.                 for usedPesticde in pesticideWork.pesticideObjectList {
  302.                     for pesticide in pesticideList {
  303.                         if(usedPesticde.pesticideRef == String(describing: pesticide.ref!)){
  304.                             let newDays = (TimeMethods.getDaysUntilDeadline(date: pesticideWork.timeFinished, numberOfDays: pesticide.processingDeadline!))
  305.                             if(newDays > days){
  306.                                 days = newDays
  307.                             }
  308.                         }
  309.                        
  310.                     }
  311.                 }
  312.             }
  313.         }
  314.         return days
  315.     }
  316.    
  317.    
  318.     func updateInfoLabel(field: Field){
  319.         let days = checkProcessingDeadline(field: field)
  320.         processingDays = days
  321.        
  322.         if(days > 0){
  323.             infoLabel.text = "you have to wait " + String(describing: days) + " days"
  324.            
  325.         } else {
  326.             infoLabel.text = "It is ok to harvest "
  327.         }
  328.         self.tableView.reloadData()
  329.     }
  330.    
  331.    
  332.     override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
  333.         if(indexPath.row == 3){
  334.             if (processingDays != nil) {
  335.                 if (processingDays! <= 0){
  336.                     cell.backgroundColor = UIColor.green
  337.                 } else {
  338.                     cell.backgroundColor = UIColor.red
  339.                 }
  340.             }
  341.  
  342.         } else {
  343.             cell.backgroundColor = UIColor.clear
  344.         }
  345.        
  346.     }
  347.  
  348.  
  349.    
  350.     //  pickerview stuff --- - - - - - -  - - - - - - - -  - - - - - - -- - - -- - - - -
  351.    
  352.    
  353.     private func fieldPickerUpdateField (number: Int) {
  354.         if (fieldList.count > 0) {
  355.             let field = fieldList[number]
  356.             fieldNameLabel.text = (field.name) + " - " + (field.crop)
  357.             selectedField = field
  358.  
  359.         }
  360.     }
  361.    
  362.    
  363.    
  364.     func numberOfComponents(in pickerView: UIPickerView) -> Int {
  365.         if pickerView == fieldPicker {
  366.             return 1
  367.         }
  368.         else {
  369.             return 1
  370.         }
  371.     }
  372.    
  373.     func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int{
  374.         if pickerView == fieldPicker {
  375.             return fieldList.count
  376.         } else {
  377.             return 0
  378.         }
  379.     }
  380.    
  381.     func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?{
  382.         if pickerView == fieldPicker {
  383.            
  384.             return fieldList[row].name
  385.         }
  386.         else {
  387.            
  388.             return ""
  389.         }
  390.     }
  391.    
  392.     func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int){
  393.         if(pickerView == fieldPicker){
  394.             if(fieldList.count > 0){
  395.                 fieldPickerUpdateField(number: row)
  396.                 selectedField = fieldList[row]
  397.                 downloadPesticideList(field: fieldList[row])
  398.             }
  399.  
  400.            
  401.             checkIfButtonCanBeEnabled()
  402.         }
  403.     }
  404.  
  405. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement