ScheduleViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. 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. NSLog("IVV Loading schedule START")
  88. // TODO: if/else for margolari/city
  89. self.context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  90. self.delegate = UIApplication.shared.delegate as? AppDelegate
  91. self.delegate?.scheduleController = self
  92. self.lang = getLanguage()
  93. self.context?.persistentStoreCoordinator = self.delegate?.persistentStoreCoordinator
  94. NSLog("IVV Loading schedule 1")
  95. // Get days
  96. // TODO: Get current year
  97. let year = 2017
  98. let dateFormatter = DateFormatter()
  99. dateFormatter.dateFormat = "yyyy-MM-dd"
  100. dateFormatter.locale = Locale.init(identifier: "en_GB")
  101. var dateString = "\(year)-01-01"
  102. let sDate = dateFormatter.date(from: dateString)
  103. dateString = "\(year)-12-31"
  104. let eDate = dateFormatter.date(from: dateString)
  105. let dayFetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Festival_event_gm")
  106. dayFetchRequest.propertiesToFetch = ["day"]
  107. NSLog("IVV Loading schedule 2")
  108. dayFetchRequest.predicate = NSPredicate(format: "(start >= %@) AND (start <= %@)", argumentArray: [sDate!, eDate!])
  109. NSLog("IVV Loading schedule 3")
  110. dayFetchRequest.returnsDistinctResults = true
  111. let sortDayDescriptor = NSSortDescriptor(key: "start", ascending: true)
  112. let sortDayDescriptors = [sortDayDescriptor]
  113. dayFetchRequest.sortDescriptors = sortDayDescriptors
  114. NSLog("IVV Loading schedule 4")
  115. do {
  116. let results = try self.context?.fetch(dayFetchRequest)
  117. NSLog("IVV Loading schedule 5")
  118. for r in results as! [NSManagedObject] {
  119. let day: NSDate = r.value(forKey: "day") as! NSDate
  120. // Don't add duplicates
  121. if self.days.contains(day) == false{
  122. self.days.append(day)
  123. }
  124. }
  125. NSLog("IVV Loading schedule 6")
  126. }
  127. catch let err as NSError {
  128. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting day list: \(err)")
  129. }
  130. // Select the day to show initially.
  131. // TODO: Check if any day corresponds to the current date.
  132. self.selectedDay = 0
  133. // Set listenerts for the arrow buttons
  134. let tapRecognizerPrevDay = UITapGestureRecognizer(target: self, action: #selector(prevDay(_:)))
  135. self.btPrev.isUserInteractionEnabled = true
  136. self.btPrev.addGestureRecognizer(tapRecognizerPrevDay)
  137. let tapRecognizerNextDay = UITapGestureRecognizer(target: self, action: #selector(nextDay(_:)))
  138. self.btNext.isUserInteractionEnabled = true
  139. self.btNext.addGestureRecognizer(tapRecognizerNextDay)
  140. NSLog("IVV Loading schedule 7")
  141. loadDay()
  142. NSLog("IVV Loading schedule END")
  143. }
  144. /**
  145. Populates the schedule list with tehe events of the currently selected days.
  146. Usually there is no need to call this function manually.
  147. */
  148. func loadDay(){
  149. let dateFormatter = DateFormatter()
  150. dateFormatter.dateFormat = "yyyy-MM-dd"
  151. dateFormatter.locale = Locale.init(identifier: "en_GB")
  152. // Clear list.
  153. for v in (self.svScheduleList?.subviews)!{
  154. v.removeFromSuperview()
  155. }
  156. if margolari == true{
  157. let dayFetchRequest: NSFetchRequest<Festival_day> = Festival_day.fetchRequest()
  158. dayFetchRequest.predicate = NSPredicate(format: "date = %@", argumentArray: [days[selectedDay]])
  159. var name: String = ""
  160. do {
  161. let daySearchResults = try self.context?.fetch(dayFetchRequest)
  162. for r in daySearchResults! {
  163. name = (r.value(forKey: "name_\(lang!)") as! String).decode()
  164. }
  165. self.lbDayName.text = name
  166. }
  167. catch {
  168. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting info about days: \(error)")
  169. }
  170. }
  171. else{
  172. self.lbDayName.text = ""
  173. }
  174. // Check for no days
  175. if self.selectedDay >= days.count || selectedDay < 0 {
  176. NSLog("SCHEDULECONTROLLER:ERROR: No schedule for day \(selectedDay)")
  177. return
  178. }
  179. let dateString: String = dateFormatter.string(from: self.days[self.selectedDay] as Date)
  180. let nDay: String = dateString.subStr(start: 8, end: 9)
  181. let month: String = dateString.subStr(start: 5, end: 6)
  182. var nMonth: String = "Agosto" // TODO: Reference
  183. if month == "07"{
  184. nMonth = "Julio" // TODO: Reference
  185. }
  186. self.lbDayMonth.text = nMonth
  187. self.lbDayNumber.text = "\(Int(nDay)!)"
  188. // Enable or disable buttons
  189. if self.selectedDay <= 0{
  190. self.btPrev.alpha = 0.5
  191. self.btPrev.isUserInteractionEnabled = false
  192. }
  193. else{
  194. self.btPrev.alpha = 1
  195. self.btPrev.isUserInteractionEnabled = true
  196. }
  197. if self.selectedDay >= (days.count - 1){
  198. self.btNext.alpha = 0.5
  199. self.btNext.isUserInteractionEnabled = false
  200. }
  201. else{
  202. self.btNext.alpha = 1
  203. self.btNext.isUserInteractionEnabled = true
  204. }
  205. var rowcount = 0
  206. var row: RowSchedule
  207. var id: Int
  208. var start: NSDate
  209. var title: String
  210. var text: String
  211. var locationId: Int
  212. var location: String
  213. do {
  214. // Get the result
  215. let searchResults: NSFetchRequest<NSFetchRequestResult>
  216. if margolari == true{
  217. let fetchRequest: NSFetchRequest<Festival_event_gm> = Festival_event_gm.fetchRequest()
  218. let sortDescriptor = NSSortDescriptor(key: "start", ascending: true)
  219. let sortDescriptors = [sortDescriptor]
  220. fetchRequest.sortDescriptors = sortDescriptors
  221. let searchResults = try self.context?.fetch(fetchRequest)
  222. for r in searchResults! {
  223. id = r.value(forKey: "id") as! Int
  224. title = r.value(forKey: "title_\(lang!)") as! String
  225. if r.value(forKey: "description_\(lang!)") != nil{
  226. text = r.value(forKey: "description_\(lang!)") as! String
  227. }
  228. else{
  229. text = ""
  230. }
  231. start = r.value(forKey: "start")! as! NSDate
  232. locationId = r.value(forKey: "place")! as! Int
  233. row = RowSchedule.init(s: "rowSchedule\(rowcount)", i: rowcount)
  234. row.setTitle(text: title)
  235. row.setText(text: text)
  236. row.setTime(dtime: start)
  237. row.id = id
  238. // Get location info from Place entity
  239. let locationFetchRequest: NSFetchRequest<Place> = Place.fetchRequest()
  240. locationFetchRequest.predicate = NSPredicate(format: "id == %i", locationId)
  241. locationFetchRequest.fetchLimit = 1
  242. do{
  243. var locationSearchResults = try self.context?.fetch(locationFetchRequest)
  244. if (locationSearchResults?.count)! > 0{
  245. let locationR = locationSearchResults?[0]
  246. location = locationR?.value(forKey: "name_\(lang!)")! as! String
  247. row.setLocation(text: location)
  248. }
  249. else{
  250. row.setLocation(text: "")
  251. }
  252. }
  253. catch {
  254. NSLog(":SCHEDULECONTROLLER:ERROR: Error getting location: \(error)")
  255. }
  256. svScheduleList.addArrangedSubview(row)
  257. rowcount = rowcount + 1
  258. }
  259. } // if margolari == true
  260. svScheduleList.setNeedsLayout()
  261. svScheduleList.layoutIfNeeded()
  262. } catch {
  263. NSLog(":SCHEDULECONTROLLER:ERROR: Error with event: \(error)")
  264. }
  265. }
  266. /**
  267. Shows the schedule of the next day
  268. :param: sender Event trigger.
  269. */
  270. func nextDay(_ sender:UITapGestureRecognizer? = nil){
  271. changeDay(increment: 1)
  272. }
  273. /**
  274. Shows the schedule of the previous day.
  275. :param: sender Event trigger.
  276. */
  277. func prevDay(_ sender:UITapGestureRecognizer? = nil){
  278. changeDay(increment: -1)
  279. }
  280. /**
  281. Changes the day by a fixed amount of days.
  282. Usualli called to move one step forward or backward.
  283. :param: increment Days to advance the schedule. Negative values to back it up.
  284. */
  285. func changeDay(increment: Int){
  286. self.selectedDay = self.selectedDay + increment
  287. if self.selectedDay <= -1{
  288. self.selectedDay = 0
  289. }
  290. if self.selectedDay >= self.days.count{
  291. self.selectedDay = (self.days.count - 1)
  292. }
  293. loadDay()
  294. }
  295. /**
  296. Shows an event dialog.
  297. :param: id The event id.
  298. */
  299. func showEvent(id: Int){
  300. NSLog(":SCHEDULECONTROLLER:DEBUG: Show event \(id)")
  301. self.passId = id
  302. performSegue(withIdentifier: "SegueEvent", sender: nil)
  303. }
  304. /**
  305. Run before performing a segue.
  306. Assigns id if neccessary.
  307. :param: segue The segue to perform.
  308. :sender: The calling view.
  309. */
  310. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  311. if segue.identifier == "SegueEvent"{
  312. (segue.destination as! EventController).id = passId
  313. }
  314. }
  315. /**
  316. Gets the device language. The only recognized languages are Spanish, English and Basque.
  317. If the device has another language, Spanish will be selected by default.
  318. :return: Two-letter language code.
  319. */
  320. func getLanguage() -> String{
  321. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  322. if(pre == "es" || pre == "en" || pre == "eu"){
  323. return pre
  324. }
  325. else{
  326. return "es"
  327. }
  328. }
  329. }