ScheduleViewController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. import UIKit
  21. import CoreData
  22. /**
  23. The controller of the schedule view.
  24. */
  25. class ScheduleViewController: UIViewController, UIGestureRecognizerDelegate {
  26. // Outlets
  27. @IBOutlet weak var lbWindowTitle: UILabel!
  28. @IBOutlet weak var btPrev: UIButton!
  29. @IBOutlet weak var btNext: UIButton!
  30. @IBOutlet weak var lbDayNumber: UILabel!
  31. @IBOutlet weak var lbDayMonth: UILabel!
  32. @IBOutlet weak var lbDayName: UILabel!
  33. @IBOutlet weak var svScheduleList: UIStackView!
  34. @IBOutlet weak var lbToolbarTitle: UILabel!
  35. @IBOutlet weak var btToolbarButton: UIButton!
  36. var context: NSManagedObjectContext? = nil
  37. var lang: String? = nil
  38. var delegate: AppDelegate? = nil
  39. // Margolari schedule indicator
  40. var margolari: Bool = false
  41. // Day indicator
  42. var days: [NSDate] = [NSDate]()
  43. var selectedDay: Int = 0
  44. // Id of event to open.
  45. var passId: Int = -1
  46. /**
  47. Gets the application context.
  48. :return: The application context.
  49. */
  50. func getContext () -> NSManagedObjectContext {
  51. return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  52. }
  53. /**
  54. Run when the app loads.
  55. */
  56. override func viewDidLoad() {
  57. super.viewDidLoad()
  58. self.loadSchedule(margolari: margolari)
  59. // Set titles
  60. if margolari == true{
  61. lbToolbarTitle.text = " Programa Margolari"
  62. lbWindowTitle.text = " Programa Margolari"
  63. }
  64. else{
  65. lbToolbarTitle.text = " Programa de Fiestas"
  66. lbWindowTitle.text = " Programa de Fiestas"
  67. }
  68. // Set back button action
  69. btToolbarButton.addTarget(self, action: #selector(self.back), for: .touchUpInside)
  70. }
  71. /**
  72. Returns to the main view controller.
  73. */
  74. @objc func back() {
  75. self.dismiss(animated: true, completion: nil)
  76. }
  77. /**
  78. Dispose of any resources that can be recreated.
  79. */
  80. override func didReceiveMemoryWarning() {
  81. super.didReceiveMemoryWarning()
  82. }
  83. /**
  84. Loads the schedule.
  85. */
  86. public func loadSchedule(margolari: Bool){
  87. // TODO: if/else for margolari/city
  88. self.context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  89. self.delegate = UIApplication.shared.delegate as? AppDelegate
  90. self.delegate?.scheduleController = self
  91. self.lang = getLanguage()
  92. self.context?.persistentStoreCoordinator = self.delegate?.persistentStoreCoordinator
  93. // Get days
  94. // TODO: Get current year
  95. let year = 2018
  96. let dateFormatter = DateFormatter()
  97. dateFormatter.dateFormat = "yyyy-MM-dd"
  98. dateFormatter.locale = Locale.init(identifier: "en_GB")
  99. var dateString = "\(year)-01-01"
  100. let sDate = dateFormatter.date(from: dateString)
  101. dateString = "\(year)-12-31"
  102. let eDate = dateFormatter.date(from: dateString)
  103. let dayFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Festival_event_gm")
  104. dayFetchRequest.propertiesToFetch = ["day"]
  105. dayFetchRequest.predicate = NSPredicate(format: "(start >= %@) AND (start <= %@)", argumentArray: [sDate!, eDate!])
  106. dayFetchRequest.returnsDistinctResults = true
  107. let sortDayDescriptor = NSSortDescriptor(key: "start", ascending: true)
  108. let sortDayDescriptors = [sortDayDescriptor]
  109. dayFetchRequest.sortDescriptors = sortDayDescriptors
  110. do {
  111. let results = try self.context?.fetch(dayFetchRequest)
  112. for r in results as! [NSManagedObject] {
  113. let day: NSDate = r.value(forKey: "day") as! NSDate
  114. // Don't add duplicates
  115. if self.days.contains(day) == false{
  116. self.days.append(day)
  117. }
  118. }
  119. }
  120. catch let err as NSError {
  121. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting day list: \(err)")
  122. }
  123. // Select the day to show initially.
  124. // TODO: Check if any day corresponds to the current date.
  125. self.selectedDay = 0
  126. // Set listenerts for the arrow buttons
  127. let tapRecognizerPrevDay = UITapGestureRecognizer(target: self, action: #selector(prevDay(_:)))
  128. self.btPrev.isUserInteractionEnabled = true
  129. self.btPrev.addGestureRecognizer(tapRecognizerPrevDay)
  130. let tapRecognizerNextDay = UITapGestureRecognizer(target: self, action: #selector(nextDay(_:)))
  131. self.btNext.isUserInteractionEnabled = true
  132. self.btNext.addGestureRecognizer(tapRecognizerNextDay)
  133. loadDay()
  134. }
  135. /**
  136. Populates the schedule list with tehe events of the currently selected days.
  137. Usually there is no need to call this function manually.
  138. */
  139. func loadDay(){
  140. let dateFormatter = DateFormatter()
  141. dateFormatter.dateFormat = "yyyy-MM-dd"
  142. dateFormatter.locale = Locale.init(identifier: "en_GB")
  143. // Clear list.
  144. DispatchQueue.main.async() {
  145. for v in (self.svScheduleList?.subviews)!{
  146. v.removeFromSuperview()
  147. }
  148. }
  149. if margolari == true{
  150. let dayFetchRequest: NSFetchRequest<Festival_day> = Festival_day.fetchRequest()
  151. if selectedDay >= 0 && selectedDay < days.count{
  152. dayFetchRequest.predicate = NSPredicate(format: "date = %@", argumentArray: [days[selectedDay]])
  153. var name: String = ""
  154. do {
  155. let daySearchResults = try self.context?.fetch(dayFetchRequest)
  156. for r in daySearchResults! {
  157. name = (r.value(forKey: "name_\(lang!)") as! String).decode()
  158. }
  159. self.lbDayName.text = name
  160. }
  161. catch{
  162. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting info about days: \(error)")
  163. }
  164. }
  165. else{
  166. NSLog(":SCHEDULECONTROLLER:ERROR: No events")
  167. }
  168. }
  169. else{
  170. self.lbDayName.text = ""
  171. }
  172. // Check for no days
  173. if self.selectedDay >= days.count || selectedDay < 0 {
  174. NSLog("SCHEDULECONTROLLER:ERROR: No schedule for day \(selectedDay)")
  175. return
  176. }
  177. let dateString: String = dateFormatter.string(from: self.days[self.selectedDay] as Date)
  178. let nDay: String = dateString.subStr(start: 8, end: 9)
  179. let month: String = dateString.subStr(start: 5, end: 6)
  180. var nMonth: String = "Agosto" // TODO: Reference
  181. if month == "07"{
  182. nMonth = "Julio" // TODO: Reference
  183. }
  184. self.lbDayMonth.text = nMonth
  185. self.lbDayNumber.text = "\(Int(nDay)!)"
  186. // Disable all arrow buttons to prevent fast clicking, which leads to the list not being cleared
  187. self.btPrev.alpha = 0.5
  188. self.btPrev.isUserInteractionEnabled = false
  189. self.btNext.alpha = 0.5
  190. self.btNext.isUserInteractionEnabled = false
  191. var rowcount = 0
  192. var row: RowSchedule
  193. var id: Int
  194. var start: NSDate
  195. var title: String
  196. var text: String
  197. var locationId: Int
  198. var location: String
  199. do {
  200. // Get the result
  201. let searchResults: NSFetchRequest<NSFetchRequestResult>
  202. if margolari == true{
  203. let fetchRequest: NSFetchRequest<Festival_event_gm> = Festival_event_gm.fetchRequest()
  204. fetchRequest.predicate = NSPredicate(format: "day = %@", days[selectedDay] as NSDate)
  205. //fetchRequest.predicate = NSPredicate(format: "day = %@", argumentArray: [days[selectedDay]])
  206. let sortDescriptor = NSSortDescriptor(key: "start", ascending: true)
  207. let sortDescriptors = [sortDescriptor]
  208. fetchRequest.sortDescriptors = sortDescriptors
  209. let searchResults = try self.context?.fetch(fetchRequest)
  210. for r in searchResults! {
  211. id = r.value(forKey: "id") as! Int
  212. title = r.value(forKey: "title_\(lang!)") as! String
  213. if r.value(forKey: "description_\(lang!)") != nil{
  214. text = r.value(forKey: "description_\(lang!)") as! String
  215. }
  216. else{
  217. text = ""
  218. }
  219. start = r.value(forKey: "start")! as! NSDate
  220. locationId = r.value(forKey: "place")! as! Int
  221. row = RowSchedule.init(s: "rowSchedule\(rowcount)", i: rowcount)
  222. row.setTitle(text: title)
  223. row.setText(text: text)
  224. row.setTime(dtime: start)
  225. row.id = id
  226. // Get location info from Place entity
  227. let locationFetchRequest: NSFetchRequest<Place> = Place.fetchRequest()
  228. locationFetchRequest.predicate = NSPredicate(format: "id == %i", locationId)
  229. locationFetchRequest.fetchLimit = 1
  230. do{
  231. var locationSearchResults = try self.context?.fetch(locationFetchRequest)
  232. if (locationSearchResults?.count)! > 0{
  233. let locationR = locationSearchResults?[0]
  234. location = locationR?.value(forKey: "name_\(lang!)")! as! String
  235. row.setLocation(text: location)
  236. }
  237. else{
  238. row.setLocation(text: "")
  239. }
  240. }
  241. catch {
  242. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting location: \(error)")
  243. }
  244. svScheduleList.addArrangedSubview(row)
  245. rowcount = rowcount + 1
  246. }
  247. } // if margolari == true
  248. else{
  249. let fetchRequest: NSFetchRequest<Festival_event> = Festival_event.fetchRequest()
  250. fetchRequest.predicate = NSPredicate(format: "day = %@", days[selectedDay] as NSDate)
  251. let sortDescriptor = NSSortDescriptor(key: "start", ascending: true)
  252. let sortDescriptors = [sortDescriptor]
  253. fetchRequest.sortDescriptors = sortDescriptors
  254. let searchResults = try self.context?.fetch(fetchRequest)
  255. for r in searchResults! {
  256. id = r.value(forKey: "id") as! Int
  257. title = r.value(forKey: "title_\(lang!)") as! String
  258. if r.value(forKey: "description_\(lang!)") != nil{
  259. text = r.value(forKey: "description_\(lang!)") as! String
  260. }
  261. else{
  262. text = ""
  263. }
  264. start = r.value(forKey: "start")! as! NSDate
  265. locationId = r.value(forKey: "place")! as! Int
  266. row = RowSchedule.init(s: "rowSchedule\(rowcount)", i: rowcount)
  267. row.setTitle(text: title)
  268. row.setText(text: text)
  269. row.setTime(dtime: start)
  270. row.id = id
  271. // Get location info from Place entity
  272. let locationFetchRequest: NSFetchRequest<Place> = Place.fetchRequest()
  273. locationFetchRequest.predicate = NSPredicate(format: "id == %i", locationId)
  274. locationFetchRequest.fetchLimit = 1
  275. do{
  276. var locationSearchResults = try self.context?.fetch(locationFetchRequest)
  277. if (locationSearchResults?.count)! > 0{
  278. let locationR = locationSearchResults?[0]
  279. location = locationR?.value(forKey: "name_\(lang!)")! as! String
  280. row.setLocation(text: location)
  281. }
  282. else{
  283. row.setLocation(text: "")
  284. }
  285. }
  286. catch {
  287. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting location: \(error)")
  288. }
  289. svScheduleList.addArrangedSubview(row)
  290. rowcount = rowcount + 1
  291. }
  292. }
  293. svScheduleList.setNeedsLayout()
  294. svScheduleList.layoutIfNeeded()
  295. // Enable buttons
  296. if self.selectedDay > 0{
  297. self.btPrev.alpha = 1
  298. self.btPrev.isUserInteractionEnabled = true
  299. }
  300. if self.selectedDay < (days.count - 1){
  301. self.btNext.alpha = 1
  302. self.btNext.isUserInteractionEnabled = true
  303. }
  304. }
  305. catch {
  306. NSLog(":SCHEDULECONTROLLER:ERROR: Error with event: \(error)")
  307. }
  308. }
  309. /**
  310. Shows the schedule of the next day
  311. :param: sender Event trigger.
  312. */
  313. @objc func nextDay(_ sender:UITapGestureRecognizer? = nil){
  314. changeDay(increment: 1)
  315. }
  316. /**
  317. Shows the schedule of the previous day.
  318. :param: sender Event trigger.
  319. */
  320. @objc func prevDay(_ sender:UITapGestureRecognizer? = nil){
  321. changeDay(increment: -1)
  322. }
  323. /**
  324. Changes the day by a fixed amount of days.
  325. Usualli called to move one step forward or backward.
  326. :param: increment Days to advance the schedule. Negative values to back it up.
  327. */
  328. func changeDay(increment: Int){
  329. self.selectedDay = self.selectedDay + increment
  330. if self.selectedDay <= -1{
  331. self.selectedDay = 0
  332. }
  333. if self.selectedDay >= self.days.count{
  334. self.selectedDay = (self.days.count - 1)
  335. }
  336. loadDay()
  337. }
  338. /**
  339. Shows an event dialog.
  340. :param: id The event id.
  341. */
  342. func showEvent(id: Int){
  343. NSLog(":SCHEDULECONTROLLER:DEBUG: Show event \(id)")
  344. if id < 0{
  345. self.passId = 0
  346. }
  347. else{
  348. self.passId = id
  349. }
  350. performSegue(withIdentifier: "SegueEvent", sender: nil)
  351. }
  352. /**
  353. Run before performing a segue.
  354. Assigns id if neccessary.
  355. :param: segue The segue to perform.
  356. :sender: The calling view.
  357. */
  358. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  359. if segue.identifier == "SegueEvent"{
  360. (segue.destination as! EventController).id = passId
  361. }
  362. }
  363. /**
  364. Gets the device language. The only recognized languages are Spanish, English and Basque.
  365. If the device has another language, Spanish will be selected by default.
  366. :return: Two-letter language code.
  367. */
  368. func getLanguage() -> String{
  369. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  370. if(pre == "es" || pre == "en" || pre == "eu"){
  371. return pre
  372. }
  373. else{
  374. return "es"
  375. }
  376. }
  377. }