ScheduleViewController.swift 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. // Copyright (C) 2016 Inigo Valentin
  2. //
  3. // This file is part of the Gasteizko Margolariak IOS app.
  4. //
  5. // The Gasteizko Margolariak IOS app is free software: you can
  6. // redistribute it and/or modify it under the terms of the
  7. // GNU General Public License as published by the Free Software
  8. // Foundation, either version 3 of the License, or (at your
  9. // option) any later version.
  10. //
  11. // The Gasteizko Margolariak IOS app is distributed in the
  12. // hope that it will be useful, but WITHOUT ANY WARRANTY;
  13. // without even the implied warranty of MERCHANTABILITY or
  14. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
  15. // Public License for more details.
  16. //
  17. // You should have received a copy of the GNU General Public
  18. // License along with the Gasteizko Margolariak IOS app.
  19. // If not, see <http://www.gnu.org/licenses/>.
  20. // TODO: Barely working. City schedule not working, GM is shown but events times are mixed.
  21. import UIKit
  22. import CoreData
  23. /**
  24. The controller of the schedule view.
  25. */
  26. class ScheduleViewController: UIViewController, UIGestureRecognizerDelegate {
  27. // Outlets
  28. @IBOutlet weak var lbWindowTitle: UILabel!
  29. @IBOutlet weak var btPrev: UIButton!
  30. @IBOutlet weak var btNext: UIButton!
  31. @IBOutlet weak var lbDayNumber: UILabel!
  32. @IBOutlet weak var lbDayMonth: UILabel!
  33. @IBOutlet weak var lbDayName: UILabel!
  34. @IBOutlet weak var svScheduleList: UIStackView!
  35. @IBOutlet weak var lbToolbarTitle: UILabel!
  36. @IBOutlet weak var btToolbarButton: UIButton!
  37. var context: NSManagedObjectContext? = nil
  38. var lang: String? = nil
  39. var delegate: AppDelegate? = nil
  40. // Margolari schedule indicator
  41. var margolari: Bool = false
  42. // Day indicator
  43. var days: [NSDate] = [NSDate]()
  44. var selectedDay: Int = 0
  45. /**
  46. Gets the application context.
  47. :return: The application context.
  48. */
  49. func getContext () -> NSManagedObjectContext {
  50. return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  51. }
  52. /**
  53. Run when the app loads.
  54. */
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. self.loadSchedule(margolari: margolari)
  58. // Set titles
  59. if margolari == true{
  60. lbToolbarTitle.text = " Programa Margolari"
  61. lbWindowTitle.text = " Programa Margolari"
  62. }
  63. else{
  64. lbToolbarTitle.text = " Programa de Fiestas"
  65. lbWindowTitle.text = " Programa de Fiestas"
  66. }
  67. // Set back button action
  68. btToolbarButton.addTarget(self, action: #selector(self.back), for: .touchUpInside)
  69. }
  70. /**
  71. Returns to the main view controller.
  72. */
  73. func back() {
  74. self.dismiss(animated: true, completion: nil)
  75. }
  76. /**
  77. Dispose of any resources that can be recreated.
  78. */
  79. override func didReceiveMemoryWarning() {
  80. super.didReceiveMemoryWarning()
  81. }
  82. /**
  83. Loads the schedule.
  84. */
  85. public func loadSchedule(margolari: Bool){
  86. self.context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  87. self.delegate = UIApplication.shared.delegate as? AppDelegate
  88. self.lang = getLanguage()
  89. self.context?.persistentStoreCoordinator = self.delegate?.persistentStoreCoordinator
  90. // Get days
  91. // TODO: Get current year
  92. let year = 2017
  93. let dateFormatter = DateFormatter()
  94. dateFormatter.dateFormat = "yyyy-MM-dd"
  95. dateFormatter.locale = Locale.init(identifier: "en_GB")
  96. var dateString = "\(year)-01-01"
  97. let sDate = dateFormatter.date(from: dateString)
  98. dateString = "\(year)-12-31"
  99. let eDate = dateFormatter.date(from: dateString)
  100. let dayFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Festival_event")
  101. dayFetchRequest.propertiesToFetch = ["day"]
  102. if self.margolari == true{
  103. dayFetchRequest.predicate = NSPredicate(format: "(gm = %i) AND (start >= %@) AND (start <= %@)", argumentArray: [1, sDate!, eDate!])
  104. }
  105. else{
  106. dayFetchRequest.predicate = NSPredicate(format: "(gm = %i) AND (start >= %@) AND (start <= %@)", argumentArray: [0, sDate!, eDate!])
  107. }
  108. dayFetchRequest.returnsDistinctResults = true
  109. do {
  110. let results = try self.context?.fetch(dayFetchRequest)
  111. for r in results as! [NSManagedObject] {
  112. let day: NSDate = r.value(forKey: "day") as! NSDate
  113. // Don't add duplicates
  114. if self.days.contains(day) == false{
  115. self.days.append(day)
  116. }
  117. }
  118. }
  119. catch let err as NSError {
  120. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting day list: \(err)")
  121. }
  122. // Select the day to show initially.
  123. // TODO: Check if any day corresponds to the current date.
  124. self.selectedDay = 0
  125. // Set listenerts for the arrow buttons
  126. let tapRecognizerPrevDay = UITapGestureRecognizer(target: self, action: #selector(prevDay(_:)))
  127. self.btPrev.isUserInteractionEnabled = true
  128. self.btPrev.addGestureRecognizer(tapRecognizerPrevDay)
  129. let tapRecognizerNextDay = UITapGestureRecognizer(target: self, action: #selector(nextDay(_:)))
  130. self.btNext.isUserInteractionEnabled = true
  131. self.btNext.addGestureRecognizer(tapRecognizerNextDay)
  132. loadDay()
  133. }
  134. /**
  135. Populates the schedule list with tehe events of the currently selected days.
  136. Usually there is no need to call this function manually.
  137. */
  138. func loadDay(){
  139. let dateFormatter = DateFormatter()
  140. dateFormatter.dateFormat = "yyyy-MM-dd"
  141. dateFormatter.locale = Locale.init(identifier: "en_GB")
  142. // Clear list.
  143. for v in (self.svScheduleList?.subviews)!{
  144. v.removeFromSuperview()
  145. }
  146. // TODO: Set toolbar elements.
  147. if margolari == true{
  148. let dayFetchRequest: NSFetchRequest<Festival_day> = Festival_day.fetchRequest()
  149. dayFetchRequest.predicate = NSPredicate(format: "date = %@", argumentArray: [days[selectedDay]])
  150. var name: String = ""
  151. do {
  152. let daySearchResults = try self.context?.fetch(dayFetchRequest)
  153. for r in daySearchResults! {
  154. name = r.value(forKey: "name_\(lang!)") as! String
  155. }
  156. self.lbDayName.text = name
  157. }
  158. catch {
  159. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting info about days: \(error)")
  160. }
  161. }
  162. else{
  163. self.lbDayName.text = ""
  164. }
  165. // Check for no days
  166. if self.selectedDay >= days.count || selectedDay < 0 {
  167. NSLog("SCHEDULECONTROLLER:ERROR: No schedule for day \(selectedDay)")
  168. return
  169. }
  170. let dateString: String = dateFormatter.string(from: self.days[self.selectedDay] as Date)
  171. let nDay: String = dateString.subStr(start: 8, end: 9)
  172. let month: String = dateString.subStr(start: 5, end: 6)
  173. var nMonth: String = "Agosto" // TODO: Reference
  174. if month == "07"{
  175. nMonth = "Julio" // TODO: Reference
  176. }
  177. self.lbDayMonth.text = nMonth
  178. self.lbDayNumber.text = "\(Int(nDay)!)"
  179. // Enable or disable buttons
  180. if self.selectedDay <= 0{
  181. self.btPrev.alpha = 0.5
  182. self.btPrev.isUserInteractionEnabled = false
  183. }
  184. else{
  185. self.btPrev.alpha = 1
  186. self.btPrev.isUserInteractionEnabled = true
  187. }
  188. if self.selectedDay >= (days.count - 1){
  189. self.btNext.alpha = 0.5
  190. self.btNext.isUserInteractionEnabled = false
  191. }
  192. else{
  193. self.btNext.alpha = 1
  194. self.btNext.isUserInteractionEnabled = true
  195. }
  196. var rowcount = 0
  197. var row: RowSchedule
  198. var start: NSDate
  199. var title: String
  200. var text: String
  201. var locationId: Int
  202. var location: String
  203. let fetchRequest: NSFetchRequest<Festival_event> = Festival_event.fetchRequest()
  204. let sortDescriptor = NSSortDescriptor(key: "start", ascending: true)
  205. let sortDescriptors = [sortDescriptor]
  206. fetchRequest.sortDescriptors = sortDescriptors
  207. if margolari == true{
  208. fetchRequest.predicate = NSPredicate(format: "(gm = %i) AND (day = %@)", argumentArray: [1, days[selectedDay]])
  209. }
  210. else{
  211. fetchRequest.predicate = NSPredicate(format: "(gm = %i) AND (day = %@)", argumentArray: [0, days[selectedDay]])
  212. }
  213. do {
  214. // Get the result
  215. let searchResults = try self.context?.fetch(fetchRequest)
  216. for r in searchResults! {
  217. title = r.value(forKey: "title_\(lang!)") as! String
  218. if r.value(forKey: "description_\(lang!)") != nil{
  219. text = r.value(forKey: "description_\(lang!)") as! String
  220. }
  221. else{
  222. text = ""
  223. }
  224. start = r.value(forKey: "start")! as! NSDate
  225. locationId = r.value(forKey: "place")! as! Int
  226. row = RowSchedule.init(s: "rowSchedule\(rowcount)", i: rowcount)
  227. row.setTitle(text: title)
  228. row.setText(text: text)
  229. row.setTime(dtime: start)
  230. // Get location info from Place entity
  231. let locationFetchRequest: NSFetchRequest<Place> = Place.fetchRequest()
  232. locationFetchRequest.predicate = NSPredicate(format: "id == %i", locationId)
  233. locationFetchRequest.fetchLimit = 1
  234. do{
  235. var locationSearchResults = try self.context?.fetch(locationFetchRequest)
  236. let locationR = locationSearchResults?[0]
  237. location = locationR?.value(forKey: "name_\(lang!)")! as! String
  238. row.setLocation(text: location)
  239. } catch {
  240. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting location: \(error)")
  241. }
  242. svScheduleList.addArrangedSubview(row)
  243. rowcount = rowcount + 1
  244. }
  245. svScheduleList.setNeedsLayout()
  246. svScheduleList.layoutIfNeeded()
  247. } catch {
  248. NSLog(":SCHEDULECONTROLLER:ERROR: Error with event: \(error)")
  249. }
  250. }
  251. /**
  252. Shows the schedule of the next day
  253. :param: sender Event trigger.
  254. */
  255. func nextDay(_ sender:UITapGestureRecognizer? = nil){
  256. changeDay(increment: 1)
  257. }
  258. /**
  259. Shows the schedule of the previous day.
  260. :param: sender Event trigger.
  261. */
  262. func prevDay(_ sender:UITapGestureRecognizer? = nil){
  263. changeDay(increment: -1)
  264. }
  265. /**
  266. Changes the day by a fixed amount of days.
  267. Usualli called to move one step forward or backward.
  268. :param: increment Days to advance the schedule. Negative values to back it up.
  269. */
  270. func changeDay(increment: Int){
  271. self.selectedDay = self.selectedDay + increment
  272. if self.selectedDay <= -1{
  273. self.selectedDay = 0
  274. }
  275. if self.selectedDay >= self.days.count{
  276. self.selectedDay = (self.days.count - 1)
  277. }
  278. loadDay()
  279. }
  280. /**
  281. Gets the device language. The only recognized languages are Spanish, English and Basque.
  282. If the device has another language, Spanish will be selected by default.
  283. :return: Two-letter language code.
  284. */
  285. func getLanguage() -> String{
  286. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  287. if(pre == "es" || pre == "en" || pre == "eu"){
  288. return pre
  289. }
  290. else{
  291. return "es"
  292. }
  293. }
  294. }