BroadcastMembersTableViewController.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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.obscuresBackgroundDuringPresentation = false
  63. searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  64. // searchController.searchBar.updateHeight(height: 36, radius: 18)
  65. // searchController.searchBar.setMagnifyingGlassColorTo(color: .white)
  66. searchController.searchBar.setImage(UIImage(), for: .search, state: .normal)
  67. searchController.searchBar.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .search)
  68. searchController.searchBar.setCustomBackgroundImage(image: UIImage(named: self.traitCollection.userInterfaceStyle == .dark ? "nx_search_bar_dark" : "nx_search_bar", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!)
  69. searchController.searchBar.tintColor = .mainColor
  70. UIBarButtonItem.appearance(whenContainedInInstancesOf: [UISearchBar.self]).setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.white], for: .normal)
  71. navigationItem.searchController = searchController
  72. navigationItem.hidesSearchBarWhenScrolling = false
  73. let buttonAddFriend = UIBarButtonItem(image: UIImage(systemName: "plus", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(addFriend(sender:)))
  74. navigationItem.rightBarButtonItem = buttonAddFriend
  75. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  76. self.getData()
  77. })
  78. }
  79. @objc func addFriend(sender: UIBarButtonItem) {
  80. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "addFriendNav") as! UINavigationController
  81. Utils.addBackground(view: controller.view)
  82. if let vc = controller.viewControllers.first as? AddFriendTableViewController {
  83. vc.isDismiss = {
  84. self.contacts.removeAll()
  85. self.getContacts {
  86. DispatchQueue.main.async {
  87. self.tableView.reloadData()
  88. }
  89. }
  90. }
  91. }
  92. self.navigationController?.present(controller, animated: true, completion: nil)
  93. }
  94. override func viewWillAppear(_ animated: Bool) {
  95. pullBuddy()
  96. }
  97. @objc func onReload(notification: NSNotification) {
  98. getData()
  99. }
  100. // MARK: - Table view data source
  101. func getData() {
  102. contacts.removeAll()
  103. groups.removeAll()
  104. getContacts {
  105. DispatchQueue.main.async {
  106. self.tableView.reloadData()
  107. }
  108. }
  109. getGroups { g in
  110. self.groups.append(contentsOf: g)
  111. DispatchQueue.main.async {
  112. self.tableView.reloadData()
  113. }
  114. }
  115. }
  116. private func getContacts(completion: @escaping ()->()) {
  117. DispatchQueue.global().async {
  118. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  119. do {
  120. 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") {
  121. while cursorData.next() {
  122. let user = User(pin: cursorData.string(forColumnIndex: 0) ?? "",
  123. firstName: cursorData.string(forColumnIndex: 1) ?? "",
  124. lastName: cursorData.string(forColumnIndex: 2) ?? "",
  125. thumb: cursorData.string(forColumnIndex: 3) ?? "",
  126. userType: cursorData.string(forColumnIndex: 5) ?? "")
  127. if (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces) == "USR\(user.pin)" {
  128. continue
  129. }
  130. user.official = cursorData.string(forColumnIndex: 4) ?? ""
  131. if(!self.existing.contains(user.pin)){
  132. self.contacts.append(user)
  133. }
  134. }
  135. cursorData.close()
  136. }
  137. } catch {
  138. rollback.pointee = true
  139. //print(error)
  140. }
  141. completion()
  142. })
  143. }
  144. }
  145. private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
  146. var data: [Group] = []
  147. 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 "
  148. if id.isEmpty {
  149. query += "g.parent = '\(parent)'"
  150. } else {
  151. query += "g.group_id = '\(id)'"
  152. }
  153. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
  154. while cursor.next() {
  155. let group = Group(
  156. id: cursor.string(forColumnIndex: 0) ?? "",
  157. name: cursor.string(forColumnIndex: 1) ?? "",
  158. profile: cursor.string(forColumnIndex: 2) ?? "",
  159. quote: cursor.string(forColumnIndex: 3) ?? "",
  160. by: cursor.string(forColumnIndex: 4) ?? "",
  161. date: cursor.string(forColumnIndex: 5) ?? "",
  162. parent: cursor.string(forColumnIndex: 6) ?? "",
  163. chatId: "",
  164. groupType: cursor.string(forColumnIndex: 7) ?? "",
  165. isOpen: cursor.string(forColumnIndex: 8) ?? "",
  166. official: cursor.string(forColumnIndex: 9) ?? "",
  167. isEducation: cursor.string(forColumnIndex: 10) ?? "")
  168. // if group.chatId.isEmpty {
  169. // 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)
  170. // group.childs.append(lounge)
  171. // }
  172. //
  173. // if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
  174. // while topicCursor.next() {
  175. // let topic = Group(id: group.id,
  176. // name: topicCursor.string(forColumnIndex: 1) ?? "",
  177. // profile: topicCursor.string(forColumnIndex: 2) ?? "",
  178. // quote: group.quote,
  179. // by: group.by,
  180. // date: group.date,
  181. // parent: group.id,
  182. // chatId: topicCursor.string(forColumnIndex: 0) ?? "",
  183. // groupType: group.groupType,
  184. // isOpen: group.isOpen,
  185. // official: group.official,
  186. // isEducation: group.isEducation)
  187. // group.childs.append(topic)
  188. // }
  189. // topicCursor.close()
  190. // }
  191. //
  192. // if !group.id.isEmpty {
  193. // if group.official == "1" {
  194. // let idMe = UserDefaults.standard.string(forKey: "me") as String?
  195. // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
  196. // if cursorUser.string(forColumnIndex: 0) == "23" || cursorUser.string(forColumnIndex: 0) == "24" {
  197. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  198. // }
  199. // cursorUser.close()
  200. // }
  201. // } else if group.official != "1"{
  202. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  203. // }
  204. // }
  205. if(!self.existing.contains(group.id)){
  206. data.append(group)
  207. }
  208. }
  209. cursor.close()
  210. }
  211. return data
  212. }
  213. private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
  214. DispatchQueue.global().async {
  215. Database.shared.database?.inTransaction({ fmdb, rollback in
  216. completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
  217. })
  218. }
  219. }
  220. private func pullBuddy() {
  221. if let me = UserDefaults.standard.string(forKey: "me") {
  222. DispatchQueue.global().async {
  223. let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
  224. }
  225. }
  226. }
  227. override func numberOfSections(in tableView: UITableView) -> Int {
  228. // #warning Incomplete implementation, return the number of sections
  229. return 1
  230. }
  231. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  232. // #warning Incomplete implementation, return the number of rows
  233. if(isGroup){
  234. if(isFilltering){
  235. return fillteredData.count
  236. }
  237. return groups.count
  238. }
  239. else {
  240. if(isFilltering){
  241. return fillteredData.count
  242. }
  243. return contacts.count
  244. }
  245. }
  246. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  247. var cell: UITableViewCell!
  248. if(isGroup) {
  249. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
  250. var content = cell.defaultContentConfiguration()
  251. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  252. let group: Group
  253. if isFilltering {
  254. group = fillteredData[indexPath.row] as! Group
  255. } else {
  256. group = groups[indexPath.row]
  257. }
  258. content.text = group.name
  259. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  260. 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
  261. content.image = image
  262. }
  263. cell.contentConfiguration = content
  264. cell.tag = indexPath.row
  265. }
  266. else {
  267. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
  268. var content = cell.defaultContentConfiguration()
  269. let data: User
  270. if isFilltering {
  271. data = fillteredData[indexPath.row] as! User
  272. } else {
  273. data = contacts[indexPath.row]
  274. }
  275. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  276. 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
  277. content.image = image
  278. })
  279. if User.isOfficial(official_account: data.official ?? "") || User.isOfficialRegular(official_account: data.official ?? "") {
  280. 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)
  281. } else if User.isVerified(official_account: data.official ?? "") {
  282. 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)
  283. }
  284. else if User.isInternal(userType: data.userType ?? "") {
  285. 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)
  286. } else if User.isCallCenter(userType: data.userType ?? "") {
  287. // let dataCategory = CategoryCC.getDataFromServiceId(service_id: data.ex_offmp!)
  288. // if dataCategory != nil {
  289. // 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)
  290. // } else {
  291. 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)
  292. // }
  293. } else {
  294. content.text = data.fullName
  295. }
  296. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  297. cell.contentConfiguration = content
  298. cell.tag = indexPath.row
  299. }
  300. return cell
  301. }
  302. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat, colorText: UIColor = UIColor.black) -> NSAttributedString {
  303. let attachment = NSTextAttachment()
  304. attachment.image = image
  305. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  306. let attachmentStr = NSAttributedString(attachment: attachment)
  307. let mutableAttributedString = NSMutableAttributedString()
  308. mutableAttributedString.append(attachmentStr)
  309. let attributedStringColor = [NSAttributedString.Key.foregroundColor : colorText]
  310. let textString = NSAttributedString(string: text, attributes: attributedStringColor)
  311. mutableAttributedString.append(textString)
  312. return mutableAttributedString
  313. }
  314. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  315. let cell = sender as! UITableViewCell
  316. if let destination = segue.destination as? BroadcastViewController {
  317. if(isGroup){
  318. if(isFilltering){
  319. destination.groups.append(fillteredData[cell.tag] as! Group)
  320. }
  321. else {
  322. destination.groups.append(groups[cell.tag])
  323. }
  324. }
  325. else {
  326. if(isFilltering){
  327. destination.contacts.append(fillteredData[cell.tag] as! User)
  328. }
  329. else {
  330. destination.contacts.append(contacts[cell.tag])
  331. }
  332. }
  333. //print("GROUPS \(destination.groups)")
  334. //print("CONTACTS \(destination.contacts)")
  335. destination.memberTable.reloadData()
  336. destination.tableView.reloadData()
  337. }
  338. }
  339. }