FutureActivityViewController.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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. self.itineraryContainer.isHidden = true
  125. }
  126. else{
  127. var row: RowItinerary
  128. var count = 0
  129. var itiId: Int
  130. var itiTitle: String
  131. var itiText: String
  132. var itiPlace: Int
  133. var itiStart: NSDate
  134. var place: [String]
  135. for r in itiSearchResults {
  136. count = count + 1
  137. // Create a new row
  138. row = RowItinerary.init(s: "rowItinerary\(count)", i: count)
  139. itiId = r.value(forKey: "id")! as! Int
  140. itiTitle = r.value(forKey: "name_\(lang)")! as! String
  141. itiText = r.value(forKey: "description_\(lang)")! as! String
  142. itiStart = r.value(forKey: "start")! as! NSDate
  143. itiPlace = r.value(forKey: "place")! as! Int
  144. place = getPlace(place: itiPlace, lang: lang, context: context)
  145. row.setTitle(text: itiTitle)
  146. row.setText(text: itiText)
  147. row.setStart(str: formatTime(date: itiStart))
  148. row.setPlace(place: place[0], address: place[1])
  149. row.id = id
  150. self.itineraryList?.addArrangedSubview(row)
  151. }
  152. self.itineraryList?.setNeedsLayout()
  153. self.itineraryList?.layoutIfNeeded()
  154. }
  155. }
  156. catch {
  157. NSLog(":FUTUREACTIVITY:ERROR: Error getting itinerary: \(error)")
  158. }
  159. }
  160. } catch {
  161. NSLog(":FUTUREACTIVITYCONTROLLER:ERROR: Error loading past activity: \(error)")
  162. }
  163. }
  164. /**
  165. Formats a date to the desired language.
  166. :param: text The date.
  167. :param: lang Device language (only 'es', 'en', or 'eu').
  168. */
  169. func formatDate(date: NSDate, lang: String) -> String{
  170. let months_es = ["0index", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
  171. let months_en = ["0index", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  172. let months_eu = ["0index", "urtarrilaren", "otsailaren", "martxoaren", "abrilaren", "maiatzaren", "ekainaren", "ustailaren", "abustuaren", "irailaren", "urriaren", "azaroaren", "abenduaren"]
  173. let days_es = ["0index", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sábado", "Domingo"]
  174. let days_en = ["0index", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  175. let days_eu = ["0index", "Astelehena", "Asteartea", "Asteazkena", "Osteguna", "Ostirala", "Larumbata", "Igandea"]
  176. let calendar = Calendar.current
  177. let day = calendar.component(.day, from: date as Date)
  178. let month = calendar.component(.month, from: date as Date)
  179. let weekday = calendar.component(.weekday, from: date as Date)
  180. var strDate = ""
  181. switch lang{
  182. case "en":
  183. var dayNum = ""
  184. switch day{
  185. case 1:
  186. dayNum = "1th"
  187. break
  188. case 2:
  189. dayNum = "2nd"
  190. break;
  191. case 3:
  192. dayNum = "3rd"
  193. break;
  194. default:
  195. dayNum = "\(weekday)th"
  196. }
  197. strDate = "\(days_en[weekday]), \(months_en[month]) \(dayNum)"
  198. break
  199. case "eu":
  200. strDate = "\(days_eu[weekday]) \(months_eu[month]) \(day)an"
  201. break
  202. default:
  203. strDate = "\(days_es[weekday]) \(day) de \(months_es[month])"
  204. }
  205. return strDate
  206. }
  207. /**
  208. Extracts the time from a date to a string.
  209. :param: text The date.
  210. :return: Time, in string format.
  211. */
  212. func formatTime(date: NSDate) -> String{
  213. let calendar = Calendar.current
  214. let hour: Int = calendar.component(.hour, from: date as Date)
  215. let minute: Int = calendar.component(.minute, from: date as Date)
  216. var strTime = ""
  217. if minute <= 9{
  218. strTime = "\(hour):0\(minute)"
  219. }
  220. else{
  221. strTime = "\(hour):\(minute)"
  222. }
  223. return strTime
  224. }
  225. /**
  226. Gets info about a place in the device language.
  227. :param: place Place id.
  228. :param: lang Device language (only 'es', 'en', or 'eu').
  229. :param: context Application context.
  230. :return: String array. 0-index item contains the place name. The 1-index one contains the address.
  231. */
  232. func getPlace(place: Int, lang: String, context: NSManagedObjectContext) -> [String]{
  233. var placeName = ""
  234. var placeAddress = ""
  235. let fetchRequest: NSFetchRequest<Place> = Place.fetchRequest()
  236. fetchRequest.predicate = NSPredicate(format: "id = %i", place)
  237. do {
  238. let searchResults = try context.fetch(fetchRequest)
  239. let r: NSManagedObject = searchResults[0]
  240. placeName = r.value(forKey: "name_\(lang)")! as! String
  241. placeAddress = r.value(forKey: "address_\(lang)")! as! String
  242. }
  243. catch{
  244. NSLog(":FUTUREACTIVITY:ERROR: Error getting infor about place \(place): \(error)")
  245. }
  246. return [placeName, placeAddress]
  247. }
  248. /**
  249. Gets the device language. The only recognized languages are Spanish, English and Basque.
  250. If the device has another language, Spanish will be selected by default.
  251. :return: Two-letter language code.
  252. */
  253. func getLanguage() -> String{
  254. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  255. if(pre == "es" || pre == "en" || pre == "eu"){
  256. return pre
  257. }
  258. else{
  259. return "es"
  260. }
  261. }
  262. }