ScheduleViewController.swift 10 KB

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