FutureActivityViewController.swift 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. Controller to show a future activity.
  24. */
  25. class FutureActivityViewController: UIViewController, UIGestureRecognizerDelegate {
  26. @IBOutlet weak var barButton: UIButton!
  27. @IBOutlet weak var barTitle: UILabel!
  28. @IBOutlet weak var activityTitle: UILabel!
  29. @IBOutlet weak var activityImage: UIImageView!
  30. @IBOutlet weak var activityText: UILabel!
  31. @IBOutlet weak var activityDate: UILabel!
  32. @IBOutlet weak var itineraryContainer: UIView!
  33. @IBOutlet weak var itineraryList: UIStackView!
  34. @IBOutlet weak var activityPrice: UILabel!
  35. // Activity id
  36. var id: Int = -1
  37. var delegate: AppDelegate?
  38. var passId: Int = -1
  39. /**
  40. Get the app context.
  41. :return: The app context.
  42. */
  43. func getContext () -> NSManagedObjectContext {
  44. return NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
  45. }
  46. /**
  47. Run when the app loads.
  48. */
  49. override func viewDidLoad() {
  50. super.viewDidLoad()
  51. self.loadActivity(id: id)
  52. // Set button action
  53. barButton.addTarget(self, action: #selector(self.back), for: .touchUpInside)
  54. }
  55. /**
  56. Dismisses the controller.
  57. */
  58. func back() {
  59. self.dismiss(animated: true, completion: nil)
  60. }
  61. /**
  62. Dispose of any resources that can be recreated.
  63. */
  64. override func didReceiveMemoryWarning() {
  65. super.didReceiveMemoryWarning()
  66. }
  67. /**
  68. Loads the selected post.
  69. :param: id Post id.
  70. */
  71. public func loadActivity(id: Int){
  72. let context = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
  73. let appDelegate = UIApplication.shared.delegate as! AppDelegate
  74. let lang : String = getLanguage()
  75. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  76. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  77. fetchRequest.predicate = NSPredicate(format: "id = %i", id)
  78. do {
  79. let searchResults = try context.fetch(fetchRequest)
  80. var count = 0
  81. var sTitle: String
  82. var sText: String
  83. var image: String
  84. var date: NSDate
  85. var price: Int
  86. for r in searchResults as [NSManagedObject] {
  87. count = count + 1
  88. sTitle = r.value(forKey: "title_\(lang)")! as! String
  89. sText = r.value(forKey: "text_\(lang)")! as! String
  90. date = r.value(forKey: "date")! as! NSDate
  91. price = r.value(forKey: "price")! as! Int
  92. activityTitle.text = " \(sTitle.decode().stripHtml())"
  93. activityText.text = sText.decode().stripHtml()
  94. activityDate.text = formatDate(date: date, lang: lang)
  95. activityPrice.text = "Precio: \(price) €"
  96. // Get main image
  97. image = ""
  98. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  99. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  100. let imgSortDescriptors = [imgSortDescriptor]
  101. imgFetchRequest.sortDescriptors = imgSortDescriptors
  102. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  103. imgFetchRequest.fetchLimit = 1
  104. do{
  105. let imgSearchResults = try context.fetch(imgFetchRequest)
  106. for imgR in imgSearchResults as [NSManagedObject]{
  107. image = imgR.value(forKey: "image")! as! String
  108. let path = "img/actividades/preview/\(image)"
  109. self.activityImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
  110. }
  111. }
  112. catch {
  113. NSLog(":FUTUREACTIVITYCONTROLLER:ERROR: Error getting image for past activity \(id): \(error)")
  114. }
  115. // Get itinerary
  116. let itiFetchRequest: NSFetchRequest<Activity_itinerary> = Activity_itinerary.fetchRequest()
  117. let itiSortDescriptor = NSSortDescriptor(key: "start", ascending: true)
  118. let itiSortDescriptors = [itiSortDescriptor]
  119. itiFetchRequest.sortDescriptors = itiSortDescriptors
  120. itiFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  121. do {
  122. let itiSearchResults = try context.fetch(itiFetchRequest)
  123. if itiSearchResults.count == 0{
  124. NSLog(":FUTUREACTIVITY:DEBUG: No itinerary for activity \(id)")
  125. self.itineraryContainer.isHidden = true
  126. }
  127. else{
  128. var row: RowItinerary
  129. var count = 0
  130. var itiId: Int
  131. var itiTitle: String
  132. var itiText: String
  133. var itiPlace: Int
  134. var itiStart: NSDate
  135. var place: [String]
  136. for r in itiSearchResults {
  137. count = count + 1
  138. // Create a new row
  139. row = RowItinerary.init(s: "rowItinerary\(count)", i: count)
  140. itiId = r.value(forKey: "id")! as! Int
  141. itiTitle = r.value(forKey: "name_\(lang)")! as! String
  142. itiText = r.value(forKey: "description_\(lang)")! as! String
  143. itiStart = r.value(forKey: "start")! as! NSDate
  144. itiPlace = r.value(forKey: "place")! as! Int
  145. place = getPlace(place: itiPlace, lang: lang, context: context)
  146. row.setTitle(text: itiTitle)
  147. row.setText(text: itiText)
  148. row.setStart(str: formatTime(date: itiStart))
  149. row.setPlace(place: place[0], address: place[1])
  150. row.id = id
  151. self.itineraryList?.addArrangedSubview(row)
  152. }
  153. self.itineraryList?.setNeedsLayout()
  154. self.itineraryList?.layoutIfNeeded()
  155. }
  156. }
  157. catch {
  158. NSLog(":FUTUREACTIVITY:ERROR: Error getting itinerary: \(error)")
  159. }
  160. }
  161. } catch {
  162. NSLog(":FUTUREACTIVITYCONTROLLER:ERROR: Error loading past activity: \(error)")
  163. }
  164. }
  165. /**
  166. Formats a date to the desired language.
  167. :param: text The date.
  168. :param: lang Device language (only 'es', 'en', or 'eu').
  169. */
  170. func formatDate(date: NSDate, lang: String) -> String{
  171. let months_es = ["0index", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
  172. let months_en = ["0index", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  173. let months_eu = ["0index", "urtarrilaren", "otsailaren", "martxoaren", "abrilaren", "maiatzaren", "ekainaren", "ustailaren", "abustuaren", "irailaren", "urriaren", "azaroaren", "abenduaren"]
  174. let days_es = ["0index", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sábado", "Domingo"]
  175. let days_en = ["0index", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  176. let days_eu = ["0index", "Astelehena", "Asteartea", "Asteazkena", "Osteguna", "Ostirala", "Larumbata", "Igandea"]
  177. let calendar = Calendar.current
  178. let day = calendar.component(.day, from: date as Date)
  179. let month = calendar.component(.month, from: date as Date)
  180. let weekday = calendar.component(.weekday, from: date as Date)
  181. var strDate = ""
  182. switch lang{
  183. case "en":
  184. var dayNum = ""
  185. switch day{
  186. case 1:
  187. dayNum = "1th"
  188. break
  189. case 2:
  190. dayNum = "2nd"
  191. break;
  192. case 3:
  193. dayNum = "3rd"
  194. break;
  195. default:
  196. dayNum = "\(weekday)th"
  197. }
  198. strDate = "\(days_en[weekday]), \(months_en[month]) \(dayNum)"
  199. break
  200. case "eu":
  201. strDate = "\(days_eu[weekday]) \(months_eu[month]) \(day)an"
  202. break
  203. default:
  204. strDate = "\(days_es[weekday]) \(day) de \(months_es[month])"
  205. }
  206. return strDate
  207. }
  208. /**
  209. Extracts the time from a date to a string.
  210. :param: text The date.
  211. :return: Time, in string format.
  212. */
  213. func formatTime(date: NSDate) -> String{
  214. let calendar = Calendar.current
  215. let hour: Int = calendar.component(.hour, from: date as Date)
  216. let minute: Int = calendar.component(.minute, from: date as Date)
  217. var strTime = ""
  218. if minute <= 9{
  219. strTime = "\(hour):0\(minute)"
  220. }
  221. else{
  222. strTime = "\(hour):\(minute)"
  223. }
  224. return strTime
  225. }
  226. /**
  227. Gets info about a place in the device language.
  228. :param: place Place id.
  229. :param: lang Device language (only 'es', 'en', or 'eu').
  230. :param: context Application context.
  231. :return: String array. 0-index item contains the place name. The 1-index one contains the address.
  232. */
  233. func getPlace(place: Int, lang: String, context: NSManagedObjectContext) -> [String]{
  234. var placeName = ""
  235. var placeAddress = ""
  236. let fetchRequest: NSFetchRequest<Place> = Place.fetchRequest()
  237. fetchRequest.predicate = NSPredicate(format: "id = %i", place)
  238. do {
  239. let searchResults = try context.fetch(fetchRequest)
  240. let r: NSManagedObject = searchResults[0]
  241. placeName = r.value(forKey: "name_\(lang)")! as! String
  242. placeAddress = r.value(forKey: "address_\(lang)")! as! String
  243. }
  244. catch{
  245. NSLog(":FUTUREACTIVITY:ERROR: Error getting infor about place \(place): \(error)")
  246. }
  247. return [placeName, placeAddress]
  248. }
  249. /**
  250. Gets the device language. The only recognized languages are Spanish, English and Basque.
  251. If the device has another language, Spanish will be selected by default.
  252. :return: Two-letter language code.
  253. */
  254. func getLanguage() -> String{
  255. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  256. if(pre == "es" || pre == "en" || pre == "eu"){
  257. return pre
  258. }
  259. else{
  260. return "es"
  261. }
  262. }
  263. }