BroadcastMembersTableViewController.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. //
  2. // BroadcastMembersTableViewController.swift
  3. // Qmera
  4. //
  5. // Created by Kevin Maulana on 06/10/21.
  6. //
  7. import UIKit
  8. import FMDB
  9. class BroadcastMembersTableViewController: UITableViewController, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {
  10. func updateSearchResults(for searchController: UISearchController) {
  11. filterContentForSearchText(searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines))
  12. }
  13. var contacts: [User] = []
  14. var groups: [Group] = []
  15. var existing : [String] = []
  16. var isGroup = false
  17. var searchController: UISearchController!
  18. var fillteredData: [Any] = []
  19. var isSearchBarEmpty: Bool {
  20. return searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  21. }
  22. var isFilltering: Bool {
  23. return searchController.isActive && !isSearchBarEmpty
  24. }
  25. func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
  26. searchBar.showsCancelButton = true
  27. let cBtn = searchBar.value(forKey: "cancelButton") as! UIButton
  28. cBtn.setTitle("Cancel".localized(), for: .normal)
  29. }
  30. func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
  31. searchBar.showsCancelButton = false
  32. }
  33. func filterContentForSearchText(_ searchText: String) {
  34. if(isGroup){
  35. if(searchText.isEmpty){
  36. fillteredData = groups
  37. }
  38. else {
  39. fillteredData = self.groups.filter { $0.name.lowercased().contains(searchText.lowercased()) }
  40. }
  41. }
  42. else {
  43. if(searchText.isEmpty){
  44. fillteredData = contacts
  45. }
  46. else {
  47. fillteredData = self.contacts.filter { $0.fullName.lowercased().contains(searchText.lowercased()) }
  48. }
  49. }
  50. tableView.reloadData()
  51. }
  52. override func viewDidDisappear(_ animated: Bool) {
  53. UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.black], for: .normal)
  54. }
  55. override func viewDidLoad() {
  56. super.viewDidLoad()
  57. searchController = UISearchController(searchResultsController: nil)
  58. searchController.delegate = self
  59. searchController.searchResultsUpdater = self
  60. searchController.searchBar.autocapitalizationType = .none
  61. searchController.searchBar.delegate = self
  62. searchController.searchBar.barTintColor = .secondaryColor
  63. searchController.searchBar.searchTextField.backgroundColor = .secondaryColor
  64. searchController.obscuresBackgroundDuringPresentation = false
  65. searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray])
  66. searchController.searchBar.setMagnifyingGlassColorTo(color: .mainColor)
  67. searchController.searchBar.tintColor = .mainColor
  68. UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
  69. navigationItem.searchController = searchController
  70. navigationItem.hidesSearchBarWhenScrolling = false
  71. let buttonAddFriend = UIBarButtonItem(image: UIImage(systemName: "plus", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(addFriend(sender:)))
  72. navigationItem.rightBarButtonItem = buttonAddFriend
  73. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  74. self.getData()
  75. })
  76. }
  77. @objc func addFriend(sender: UIBarButtonItem) {
  78. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "addFriendNav") as! UINavigationController
  79. if let vc = controller.viewControllers.first as? AddFriendTableViewController {
  80. vc.isDismiss = {
  81. self.contacts.removeAll()
  82. self.getContacts {
  83. DispatchQueue.main.async {
  84. self.tableView.reloadData()
  85. }
  86. }
  87. }
  88. }
  89. self.navigationController?.present(controller, animated: true, completion: nil)
  90. }
  91. override func viewWillAppear(_ animated: Bool) {
  92. pullBuddy()
  93. }
  94. @objc func onReload(notification: NSNotification) {
  95. getData()
  96. }
  97. // MARK: - Table view data source
  98. func getData() {
  99. contacts.removeAll()
  100. groups.removeAll()
  101. getContacts {
  102. DispatchQueue.main.async {
  103. self.tableView.reloadData()
  104. }
  105. }
  106. getGroups { g in
  107. self.groups.append(contentsOf: g)
  108. DispatchQueue.main.async {
  109. self.tableView.reloadData()
  110. }
  111. }
  112. }
  113. private func getContacts(completion: @escaping ()->()) {
  114. DispatchQueue.global().async {
  115. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  116. do {
  117. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: "SELECT f_pin, first_name, last_name, image_id, official_account, user_type FROM BUDDY where f_pin <> '\(UserDefaults.standard.string(forKey: "me")!)' order by 5 desc, 2 collate nocase asc") {
  118. while cursorData.next() {
  119. let user = User(pin: cursorData.string(forColumnIndex: 0) ?? "",
  120. firstName: cursorData.string(forColumnIndex: 1) ?? "",
  121. lastName: cursorData.string(forColumnIndex: 2) ?? "",
  122. thumb: cursorData.string(forColumnIndex: 3) ?? "",
  123. userType: cursorData.string(forColumnIndex: 5) ?? "")
  124. if (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces) == "USR\(user.pin)" {
  125. continue
  126. }
  127. user.official = cursorData.string(forColumnIndex: 4) ?? ""
  128. if(!self.existing.contains(user.pin)){
  129. self.contacts.append(user)
  130. }
  131. }
  132. cursorData.close()
  133. }
  134. } catch {
  135. rollback.pointee = true
  136. //print(error)
  137. }
  138. completion()
  139. })
  140. }
  141. }
  142. private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
  143. var data: [Group] = []
  144. var query = "select g.group_id, g.f_name, g.image_id, g.quote, g.created_by, g.created_date, g.parent, g.group_type, g.is_open, g.official, g.is_education from GROUPZ g where "
  145. if id.isEmpty {
  146. query += "g.parent = '\(parent)'"
  147. } else {
  148. query += "g.group_id = '\(id)'"
  149. }
  150. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
  151. while cursor.next() {
  152. let group = Group(
  153. id: cursor.string(forColumnIndex: 0) ?? "",
  154. name: cursor.string(forColumnIndex: 1) ?? "",
  155. profile: cursor.string(forColumnIndex: 2) ?? "",
  156. quote: cursor.string(forColumnIndex: 3) ?? "",
  157. by: cursor.string(forColumnIndex: 4) ?? "",
  158. date: cursor.string(forColumnIndex: 5) ?? "",
  159. parent: cursor.string(forColumnIndex: 6) ?? "",
  160. chatId: "",
  161. groupType: cursor.string(forColumnIndex: 7) ?? "",
  162. isOpen: cursor.string(forColumnIndex: 8) ?? "",
  163. official: cursor.string(forColumnIndex: 9) ?? "",
  164. isEducation: cursor.string(forColumnIndex: 10) ?? "")
  165. // if group.chatId.isEmpty {
  166. // let lounge = Group(id: group.id, name: "Lounge".localized(), profile: "", quote: group.quote, by: group.by, date: group.date, parent: group.id, chatId: group.chatId, groupType: group.groupType, isOpen: group.isOpen, official: group.official, isEducation: group.isEducation, isLounge: true)
  167. // group.childs.append(lounge)
  168. // }
  169. //
  170. // if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
  171. // while topicCursor.next() {
  172. // let topic = Group(id: group.id,
  173. // name: topicCursor.string(forColumnIndex: 1) ?? "",
  174. // profile: topicCursor.string(forColumnIndex: 2) ?? "",
  175. // quote: group.quote,
  176. // by: group.by,
  177. // date: group.date,
  178. // parent: group.id,
  179. // chatId: topicCursor.string(forColumnIndex: 0) ?? "",
  180. // groupType: group.groupType,
  181. // isOpen: group.isOpen,
  182. // official: group.official,
  183. // isEducation: group.isEducation)
  184. // group.childs.append(topic)
  185. // }
  186. // topicCursor.close()
  187. // }
  188. //
  189. // if !group.id.isEmpty {
  190. // if group.official == "1" {
  191. // let idMe = UserDefaults.standard.string(forKey: "me") as String?
  192. // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
  193. // if cursorUser.string(forColumnIndex: 0) == "23" || cursorUser.string(forColumnIndex: 0) == "24" {
  194. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  195. // }
  196. // cursorUser.close()
  197. // }
  198. // } else if group.official != "1"{
  199. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  200. // }
  201. // }
  202. if(!self.existing.contains(group.id)){
  203. data.append(group)
  204. }
  205. }
  206. cursor.close()
  207. }
  208. return data
  209. }
  210. private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
  211. DispatchQueue.global().async {
  212. Database.shared.database?.inTransaction({ fmdb, rollback in
  213. completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
  214. })
  215. }
  216. }
  217. private func pullBuddy() {
  218. if let me = UserDefaults.standard.string(forKey: "me") {
  219. DispatchQueue.global().async {
  220. let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
  221. }
  222. }
  223. }
  224. override func numberOfSections(in tableView: UITableView) -> Int {
  225. // #warning Incomplete implementation, return the number of sections
  226. return 1
  227. }
  228. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  229. // #warning Incomplete implementation, return the number of rows
  230. if(isGroup){
  231. if(isFilltering){
  232. return fillteredData.count
  233. }
  234. return groups.count
  235. }
  236. else {
  237. if(isFilltering){
  238. return fillteredData.count
  239. }
  240. return contacts.count
  241. }
  242. }
  243. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  244. var cell: UITableViewCell!
  245. if(isGroup) {
  246. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
  247. var content = cell.defaultContentConfiguration()
  248. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  249. let group: Group
  250. if isFilltering {
  251. group = fillteredData[indexPath.row] as! Group
  252. } else {
  253. group = groups[indexPath.row]
  254. }
  255. content.text = group.name
  256. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  257. getImage(name: group.profile, placeholderImage: UIImage(named: "Conversation---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath) { result, isDownloaded, image in
  258. content.image = image
  259. }
  260. cell.contentConfiguration = content
  261. cell.tag = indexPath.row
  262. }
  263. else {
  264. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
  265. var content = cell.defaultContentConfiguration()
  266. let data: User
  267. if isFilltering {
  268. data = fillteredData[indexPath.row] as! User
  269. } else {
  270. data = contacts[indexPath.row]
  271. }
  272. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  273. getImage(name: data.thumb, placeholderImage: UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath, completion: { result, isDownloaded, image in
  274. content.image = image
  275. })
  276. if User.isOfficial(official_account: data.official ?? "") || User.isOfficialRegular(official_account: data.official ?? "") {
  277. content.attributedText = self.set(image: UIImage(named: "ic_official_flag", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(data.fullName)", size: 15, y: -4, colorText: UIColor.officialColor)
  278. } else if User.isVerified(official_account: data.official ?? "") {
  279. content.attributedText = self.set(image: UIImage(named: "ic_verified", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(data.fullName)", size: 15, y: -4, colorText: UIColor.verifiedColor)
  280. }
  281. else if User.isInternal(userType: data.userType ?? "") {
  282. content.attributedText = self.set(image: UIImage(named: "ic_internal", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(data.fullName)", size: 15, y: -4, colorText: UIColor.internalColor)
  283. } else if User.isCallCenter(userType: data.userType ?? "") {
  284. // let dataCategory = CategoryCC.getDataFromServiceId(service_id: data.ex_offmp!)
  285. // if dataCategory != nil {
  286. // content.attributedText = self.set(image: UIImage(named: "pb_call_center", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(data.fullName) (\(dataCategory!.service_name))", size: 15, y: -4, colorText: UIColor.ccColor)
  287. // } else {
  288. content.attributedText = self.set(image: UIImage(named: "pb_call_center", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(data.fullName)", size: 15, y: -4, colorText: UIColor.ccColor)
  289. // }
  290. } else {
  291. content.text = data.fullName
  292. }
  293. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  294. cell.contentConfiguration = content
  295. cell.tag = indexPath.row
  296. }
  297. return cell
  298. }
  299. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat, colorText: UIColor = UIColor.black) -> NSAttributedString {
  300. let attachment = NSTextAttachment()
  301. attachment.image = image
  302. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  303. let attachmentStr = NSAttributedString(attachment: attachment)
  304. let mutableAttributedString = NSMutableAttributedString()
  305. mutableAttributedString.append(attachmentStr)
  306. let attributedStringColor = [NSAttributedString.Key.foregroundColor : colorText]
  307. let textString = NSAttributedString(string: text, attributes: attributedStringColor)
  308. mutableAttributedString.append(textString)
  309. return mutableAttributedString
  310. }
  311. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  312. let cell = sender as! UITableViewCell
  313. if let destination = segue.destination as? BroadcastViewController {
  314. if(isGroup){
  315. if(isFilltering){
  316. destination.groups.append(fillteredData[cell.tag] as! Group)
  317. }
  318. else {
  319. destination.groups.append(groups[cell.tag])
  320. }
  321. }
  322. else {
  323. if(isFilltering){
  324. destination.contacts.append(fillteredData[cell.tag] as! User)
  325. }
  326. else {
  327. destination.contacts.append(contacts[cell.tag])
  328. }
  329. }
  330. //print("GROUPS \(destination.groups)")
  331. //print("CONTACTS \(destination.contacts)")
  332. destination.memberTable.reloadData()
  333. destination.tableView.reloadData()
  334. }
  335. }
  336. }