ActivitiesView.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 Foundation
  21. import CoreData
  22. import UIKit
  23. /**
  24. Class to handle the home view.
  25. */
  26. class ActivitiesView: UIView {
  27. @IBOutlet var container: ActivitiesView!
  28. @IBOutlet weak var futureSection: Section!
  29. @IBOutlet weak var pastSection: Section!
  30. var delegate: AppDelegate? = nil
  31. var storyboard: UIStoryboard? = nil
  32. var controller: ViewController? = nil
  33. var lang: String? = nil
  34. var futureList: UIStackView? = nil
  35. var pastList: UIStackView? = nil
  36. var context: NSManagedObjectContext? = nil
  37. // Section row list
  38. var pastRows: Array<RowPastActivity> = []
  39. var futureRows: Array<RowFutureActivity> = []
  40. override init(frame: CGRect){
  41. super.init(frame: frame)
  42. }
  43. /**
  44. Run when the view is started.
  45. */
  46. required init?(coder aDecoder: NSCoder) {
  47. super.init(coder: aDecoder)
  48. //Load the contents of the HomeView.xib file.
  49. Bundle.main.loadNibNamed("ActivitiesView", owner: self, options: nil)
  50. self.addSubview(container)
  51. self.container.frame = self.bounds
  52. self.futureSection.setTitle(text: "Próximas actividades")
  53. self.pastSection.setTitle(text: "Últimas actividades")
  54. self.futureList = self.futureSection.getContentStack()
  55. self.pastList = self.pastSection.getContentStack()
  56. // Get viewController from StoryBoard
  57. self.storyboard = UIStoryboard(name: "Main", bundle: nil)
  58. self.controller = self.storyboard?.instantiateViewController(withIdentifier: "GMViewController") as? ViewController
  59. self.context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  60. self.delegate = UIApplication.shared.delegate as? AppDelegate
  61. self.lang = self.getLanguage()
  62. self.context?.persistentStoreCoordinator = self.delegate?.persistentStoreCoordinator
  63. // Populate activity lists.
  64. populate()
  65. }
  66. /**
  67. Actually populates the section.
  68. */
  69. func populate(){
  70. // Show future activities
  71. var fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  72. var sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
  73. var sortDescriptors = [sortDescriptor]
  74. fetchRequest.sortDescriptors = sortDescriptors
  75. fetchRequest.predicate = NSPredicate(format: "date > %@", NSDate())
  76. do {
  77. let searchResults = try self.context?.fetch(fetchRequest)
  78. if searchResults?.count == 0{
  79. NSLog(":ACTIVITIES:DEBUG: No future activities: \(String(describing: searchResults?.count))")
  80. let row: RowLabel = RowLabel.init(s: "rowFutureActivity0", i: 0)
  81. row.setText(text: "No hay actividades planeadas proximamente. Pronto organizaremos algo!")
  82. self.futureList?.addArrangedSubview(row)
  83. }
  84. else{
  85. var row : RowFutureActivity
  86. var count = 0
  87. var id: Int
  88. var title: String
  89. var text: String
  90. var image: String
  91. var city: String
  92. var price: Int
  93. var date: NSDate
  94. for r in searchResults! {
  95. count = count + 1
  96. // Create a new row
  97. row = RowFutureActivity.init(s: "rowFutureActivity\(count)", i: count)
  98. id = r.value(forKey: "id")! as! Int
  99. title = r.value(forKey: "title_\(lang!)")! as! String
  100. text = r.value(forKey: "text_\(lang!)")! as! String
  101. city = r.value(forKey: "city")! as! String
  102. price = r.value(forKey: "price")! as! Int
  103. date = r.value(forKey: "date")! as! NSDate
  104. row.setTitle(text: title)
  105. row.setText(text: text)
  106. row.setPrice(price: price)
  107. row.setCity(text: city)
  108. row.setDate(date: date, lang: lang!)
  109. row.id = id
  110. // Get main image
  111. image = ""
  112. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  113. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  114. let imgSortDescriptors = [imgSortDescriptor]
  115. imgFetchRequest.sortDescriptors = imgSortDescriptors
  116. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  117. imgFetchRequest.fetchLimit = 1
  118. do{
  119. let imgSearchResults = try self.context?.fetch(imgFetchRequest)
  120. for imgR in imgSearchResults!{
  121. image = imgR.value(forKey: "image")! as! String
  122. row.setImage(filename: image)
  123. }
  124. } catch {
  125. NSLog(":ACTIVITIES:ERROR: Error getting image for activity \(id): \(error)")
  126. }
  127. self.futureList?.addArrangedSubview(row)
  128. self.futureRows.append(row)
  129. // TODO: Do this on the row didLoad method
  130. // Set tap recognizer
  131. //let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openActivity(_:)))
  132. //row.isUserInteractionEnabled = true
  133. //row.addGestureRecognizer(tapRecognizer)
  134. }
  135. self.futureList?.setNeedsLayout()
  136. self.futureList?.layoutIfNeeded()
  137. }
  138. }
  139. catch {
  140. NSLog(":ACTIVITIES:ERROR: Error with request: \(error)")
  141. }
  142. setUpFutureRowsTapRecognizers()
  143. // Show past activities
  144. fetchRequest = Activity.fetchRequest()
  145. sortDescriptor = NSSortDescriptor(key: "date", ascending: false)
  146. sortDescriptors = [sortDescriptor]
  147. fetchRequest.sortDescriptors = sortDescriptors
  148. fetchRequest.predicate = NSPredicate(format: "date < %@", NSDate())
  149. do {
  150. let searchResults = try self.context?.fetch(fetchRequest)
  151. var row: RowPastActivity
  152. var count: Int = 0
  153. var id: Int
  154. var title: String
  155. var text: String
  156. var image: String
  157. for r in searchResults! {
  158. count = count + 1
  159. // Create a new row
  160. row = RowPastActivity.init(s: "rowPastActivity\(count)", i: count)
  161. id = r.value(forKey: "id")! as! Int
  162. title = r.value(forKey: "title_\(lang!)")! as! String
  163. text = r.value(forKey: "text_\(lang!)")! as! String
  164. row.setTitle(text: title)
  165. row.setText(text: text)
  166. row.id = id
  167. // Get main image
  168. image = ""
  169. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  170. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  171. let imgSortDescriptors = [imgSortDescriptor]
  172. imgFetchRequest.sortDescriptors = imgSortDescriptors
  173. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  174. imgFetchRequest.fetchLimit = 1
  175. do{
  176. let imgSearchResults = try self.context?.fetch(imgFetchRequest)
  177. for imgR in imgSearchResults!{
  178. image = imgR.value(forKey: "image")! as! String
  179. row.setImage(filename: image)
  180. }
  181. }
  182. catch {
  183. NSLog(":ACTIVITIES:ERROR: Error getting image for activity \(id): \(error)")
  184. }
  185. self.pastList?.addArrangedSubview(row)
  186. self.pastRows.append(row)
  187. // TODO: Do this on the row didLoad method
  188. // Set tap recognizer
  189. //let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(openActivity(_:)))
  190. //row.isUserInteractionEnabled = true
  191. //row.addGestureRecognizer(tapRecognizer)
  192. }
  193. self.pastList?.setNeedsLayout()
  194. self.pastList?.layoutIfNeeded()
  195. } catch {
  196. NSLog(":ACTIVITIES:ERROR: Error with request: \(error)")
  197. }
  198. //setUpPastRowsTapRecognizers()
  199. NSLog(":ACTIVITIES:DEBUG: Finished loading ActivitiesView")
  200. }
  201. /*func openActivity(){//(_ sender:UITapGestureRecognizer? = nil){
  202. NSLog(":ACTIVITIES:DEBUG: getting delegate and showing activity.")
  203. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  204. delegate.controller?.showActivity(id: 4)
  205. NSLog(":ACTIVITIES:DEBUG: Activity should be shown.")
  206. }
  207. func openActivity(_ sender:UITapGestureRecognizer? = nil){
  208. NSLog(":ACTIVITIES:DEBUG: getting delegate and showing activity.")
  209. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  210. delegate.controller?.showActivity(id: 4)
  211. NSLog(":ACTIVITIES:DEBUG: Activity should be shown.")
  212. }*/
  213. /**
  214. Handles the click events to open past activities.
  215. */
  216. func setUpPastRowsTapRecognizers(){
  217. NSLog(":ACTIVITIES:DEBUG: Setting up past activitiesr tap recognizers")
  218. for row in self.pastRows{
  219. let tapRecognizer = UITapGestureRecognizer(target: row, action: #selector(openPastActivity(_:)))
  220. row.isUserInteractionEnabled = true
  221. row.addGestureRecognizer(tapRecognizer)
  222. }
  223. }
  224. /**
  225. Opens a past activity.
  226. */
  227. func openPastActivity(_ sender:UITapGestureRecognizer? = nil){
  228. NSLog(":ACTIVITIES:DEBUG: opening pastActivity.")
  229. let id = (sender?.view as! RowPastActivity).id
  230. NSLog(":ACTIVITIES:DEBUG: getting delegate and showing pastActivity \(id).")
  231. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  232. delegate.controller?.showPastActivity(id: id)
  233. }
  234. /**
  235. Handles the click events to open past activities.
  236. */
  237. func setUpFutureRowsTapRecognizers(){
  238. NSLog(":ACTIVITIES:DEBUG: Setting up future activities tap recognizers")
  239. for row in self.futureRows{
  240. let tapRecognizer = UITapGestureRecognizer(target: row, action: #selector(openFutureActivity(_:)))
  241. row.isUserInteractionEnabled = true
  242. //container.addGestureRecognizer(tapRecognizer)
  243. }
  244. }
  245. /**
  246. Opens a past activity.
  247. */
  248. func openFutureActivity(_ sender:UITapGestureRecognizer? = nil){
  249. let id = (sender?.view as! RowFutureActivity).id
  250. NSLog(":ACTIVITIES:DEBUG: getting delegate and showing pastActivity \(id).")
  251. let delegate: AppDelegate = UIApplication.shared.delegate as! AppDelegate
  252. delegate.controller?.showFutureActivity(id: id)
  253. }
  254. /**
  255. Gets the device language. The only recognized languages are Spanish, English and Basque.
  256. If the device has another language, Spanish will be selected by default.
  257. :return: Two-letter language code.
  258. */
  259. func getLanguage() -> String{
  260. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  261. if(pre == "es" || pre == "en" || pre == "eu"){
  262. return pre
  263. }
  264. else{
  265. return "es"
  266. }
  267. }
  268. }