FutureActivityViewController.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. @objc 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. appDelegate.futureActivityController = self
  75. let lang : String = getLanguage()
  76. context.persistentStoreCoordinator = appDelegate.persistentStoreCoordinator
  77. let fetchRequest: NSFetchRequest<Activity> = Activity.fetchRequest()
  78. fetchRequest.predicate = NSPredicate(format: "id = %i", id)
  79. do {
  80. let searchResults = try context.fetch(fetchRequest)
  81. var count = 0
  82. var sTitle: String
  83. var sText: String
  84. var image: String
  85. var date: NSDate
  86. var price: Int
  87. for r in searchResults as [NSManagedObject] {
  88. count = count + 1
  89. sTitle = r.value(forKey: "title_\(lang)")! as! String
  90. sText = r.value(forKey: "text_\(lang)")! as! String
  91. date = r.value(forKey: "date")! as! NSDate
  92. price = r.value(forKey: "price")! as! Int
  93. activityTitle.text = " \(sTitle.decode().stripHtml())"
  94. activityText.text = sText.decode().stripHtml()
  95. activityDate.text = formatDate(date: date, lang: lang)
  96. activityPrice.text = "Precio: \(price) €"
  97. // Get main image
  98. image = ""
  99. let imgFetchRequest: NSFetchRequest<Activity_image> = Activity_image.fetchRequest()
  100. let imgSortDescriptor = NSSortDescriptor(key: "idx", ascending: true)
  101. let imgSortDescriptors = [imgSortDescriptor]
  102. imgFetchRequest.sortDescriptors = imgSortDescriptors
  103. imgFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  104. imgFetchRequest.fetchLimit = 1
  105. do{
  106. let imgSearchResults = try context.fetch(imgFetchRequest)
  107. for imgR in imgSearchResults as [NSManagedObject]{
  108. image = imgR.value(forKey: "image")! as! String
  109. let path = "img/actividades/preview/\(image)"
  110. self.activityImage.setImage(localPath: path, remotePath: "https://margolariak.com/\(path)")
  111. }
  112. }
  113. catch {
  114. NSLog(":FUTUREACTIVITYCONTROLLER:ERROR: Error getting image for past activity \(id): \(error)")
  115. }
  116. // Get itinerary
  117. let itiFetchRequest: NSFetchRequest<Activity_itinerary> = Activity_itinerary.fetchRequest()
  118. let itiSortDescriptor = NSSortDescriptor(key: "start", ascending: true)
  119. let itiSortDescriptors = [itiSortDescriptor]
  120. itiFetchRequest.sortDescriptors = itiSortDescriptors
  121. itiFetchRequest.predicate = NSPredicate(format: "activity == %i", id)
  122. do {
  123. let itiSearchResults = try context.fetch(itiFetchRequest)
  124. if itiSearchResults.count == 0{
  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. if r.value(forKey: "description_\(lang)") != nil{
  143. itiText = r.value(forKey: "description_\(lang)")! as! String
  144. }
  145. else{
  146. itiText = ""
  147. }
  148. itiStart = r.value(forKey: "start")! as! NSDate
  149. itiPlace = r.value(forKey: "place")! as! Int
  150. place = getPlace(place: itiPlace, lang: lang, context: context)
  151. row.setTitle(text: itiTitle)
  152. row.setText(text: itiText)
  153. row.setStart(str: formatTime(date: itiStart))
  154. row.setPlace(place: place[0], address: place[1])
  155. row.id = id
  156. self.itineraryList?.addArrangedSubview(row)
  157. }
  158. self.itineraryList?.setNeedsLayout()
  159. self.itineraryList?.layoutIfNeeded()
  160. }
  161. }
  162. catch {
  163. NSLog(":FUTUREACTIVITY:ERROR: Error getting itinerary: \(error)")
  164. }
  165. }
  166. } catch {
  167. NSLog(":FUTUREACTIVITYCONTROLLER:ERROR: Error loading past activity: \(error)")
  168. }
  169. }
  170. /**
  171. Formats a date to the desired language.
  172. :param: text The date.
  173. :param: lang Device language (only 'es', 'en', or 'eu').
  174. */
  175. func formatDate(date: NSDate, lang: String) -> String{
  176. let months_es = ["0index", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre"]
  177. let months_en = ["0index", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
  178. let months_eu = ["0index", "urtarrilaren", "otsailaren", "martxoaren", "abrilaren", "maiatzaren", "ekainaren", "ustailaren", "abustuaren", "irailaren", "urriaren", "azaroaren", "abenduaren"]
  179. let days_es = ["0index", "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sábado", "Domingo"]
  180. let days_en = ["0index", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
  181. let days_eu = ["0index", "Astelehena", "Asteartea", "Asteazkena", "Osteguna", "Ostirala", "Larumbata", "Igandea"]
  182. let calendar = Calendar.current
  183. let day = calendar.component(.day, from: date as Date)
  184. let month = calendar.component(.month, from: date as Date)
  185. let weekday = calendar.component(.weekday, from: date as Date)
  186. var strDate = ""
  187. switch lang{
  188. case "en":
  189. var dayNum = ""
  190. switch day{
  191. case 1:
  192. dayNum = "1th"
  193. break
  194. case 2:
  195. dayNum = "2nd"
  196. break;
  197. case 3:
  198. dayNum = "3rd"
  199. break;
  200. default:
  201. dayNum = "\(weekday)th"
  202. }
  203. strDate = "\(days_en[weekday]), \(months_en[month]) \(dayNum)"
  204. break
  205. case "eu":
  206. strDate = "\(days_eu[weekday]) \(months_eu[month]) \(day)an"
  207. break
  208. default:
  209. strDate = "\(days_es[weekday]) \(day) de \(months_es[month])"
  210. }
  211. return strDate
  212. }
  213. /**
  214. Extracts the time from a date to a string.
  215. :param: text The date.
  216. :return: Time, in string format.
  217. */
  218. func formatTime(date: NSDate) -> String{
  219. let calendar = Calendar.current
  220. let hour: Int = calendar.component(.hour, from: date as Date)
  221. let minute: Int = calendar.component(.minute, from: date as Date)
  222. var strTime = ""
  223. if minute <= 9{
  224. strTime = "\(hour):0\(minute)"
  225. }
  226. else{
  227. strTime = "\(hour):\(minute)"
  228. }
  229. return strTime
  230. }
  231. /**
  232. Gets info about a place in the device language.
  233. :param: place Place id.
  234. :param: lang Device language (only 'es', 'en', or 'eu').
  235. :param: context Application context.
  236. :return: String array. 0-index item contains the place name. The 1-index one contains the address.
  237. */
  238. func getPlace(place: Int, lang: String, context: NSManagedObjectContext) -> [String]{
  239. var placeName = ""
  240. var placeAddress = ""
  241. let fetchRequest: NSFetchRequest<Place> = Place.fetchRequest()
  242. fetchRequest.predicate = NSPredicate(format: "id = %i", place)
  243. do {
  244. let searchResults = try context.fetch(fetchRequest)
  245. let r: NSManagedObject = searchResults[0]
  246. placeName = r.value(forKey: "name_\(lang)")! as! String
  247. placeAddress = r.value(forKey: "address_\(lang)")! as! String
  248. }
  249. catch{
  250. NSLog(":FUTUREACTIVITY:ERROR: Error getting infor about place \(place): \(error)")
  251. }
  252. return [placeName, placeAddress]
  253. }
  254. /**
  255. Shows an itinerary dialog.
  256. :param: id The itinerary id.
  257. */
  258. func showItinerary(id: Int){
  259. self.passId = id
  260. // TODO
  261. NSLog(":FUTUREACTIVITY:TODO: Implement segue")
  262. //performSegue(withIdentifier: "SegueItinerary", sender: nil)
  263. }
  264. /**
  265. Run before performing a segue.
  266. Assigns id if neccessary.
  267. :param: segue The segue to perform.
  268. :sender: The calling view.
  269. */
  270. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  271. if segue.identifier == "SegueItinerary"{
  272. (segue.destination as! EventController).id = passId
  273. }
  274. }
  275. /**
  276. Gets the device language. The only recognized languages are Spanish, English and Basque.
  277. If the device has another language, Spanish will be selected by default.
  278. :return: Two-letter language code.
  279. */
  280. func getLanguage() -> String{
  281. let pre = NSLocale.preferredLanguages[0].subStr(start: 0, end: 1)
  282. if(pre == "es" || pre == "en" || pre == "eu"){
  283. return pre
  284. }
  285. else{
  286. return "es"
  287. }
  288. }
  289. }