GroupMemberViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. //
  2. // GroupMemberViewController.swift
  3. // Qmera
  4. //
  5. // Created by Yayan Dwi on 30/09/21.
  6. //
  7. import UIKit
  8. class GroupMemberViewController: UITableViewController {
  9. private var searchController: UISearchController!
  10. var group: Group!
  11. var isDismiss: (() -> ())?
  12. var isContactCenterInvite = false
  13. private var availableUser: [User] = []
  14. private var fillteredUser: [User] = []
  15. private var isSearchBarEmpty: Bool {
  16. return searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
  17. }
  18. private var isFilltering: Bool {
  19. return searchController.isActive && !isSearchBarEmpty
  20. }
  21. private var userSelected: [User] = []
  22. override func viewDidLoad() {
  23. super.viewDidLoad()
  24. title = "Add New Member(s)".localized()
  25. navigationController?.navigationBar.backgroundColor = self.traitCollection.userInterfaceStyle == .dark ? .blackDarkMode : .mainColor
  26. navigationController?.navigationBar.prefersLargeTitles = true
  27. navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(add(sender:)))
  28. navigationItem.rightBarButtonItem?.isEnabled = false
  29. navigationItem.rightBarButtonItem?.tintColor = .white
  30. searchController = UISearchController(searchResultsController: nil)
  31. searchController.delegate = self
  32. searchController.searchResultsUpdater = self
  33. searchController.searchBar.autocapitalizationType = .none
  34. searchController.searchBar.delegate = self
  35. searchController.searchBar.barTintColor = .secondaryColor
  36. searchController.searchBar.searchTextField.backgroundColor = .secondaryColor
  37. searchController.obscuresBackgroundDuringPresentation = false
  38. searchController.searchBar.searchTextField.attributedPlaceholder = NSAttributedString(string: "Search".localized(), attributes: [NSAttributedString.Key.foregroundColor: UIColor.gray, NSAttributedString.Key.font: UIFont.systemFont(ofSize: 16)])
  39. definesPresentationContext = true
  40. navigationItem.searchController = searchController
  41. navigationItem.hidesSearchBarWhenScrolling = true
  42. getData { users in
  43. self.availableUser.append(contentsOf: users)
  44. DispatchQueue.main.async {
  45. self.tableView.reloadData()
  46. }
  47. }
  48. }
  49. @objc func add(sender: Any) {
  50. DispatchQueue.global().async {
  51. Database.shared.database?.inTransaction({ fmdb, rollback in
  52. var result: Int = 0
  53. for u in self.userSelected {
  54. if let response = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddGroupMember(p_group_id: self.group.id, p_member_pin: u.pin, p_position: "0")), response.isOk() {
  55. let arrayChatId = self.group.topics.filter({ t in
  56. return t.title != "Lounge".localized()
  57. }).map { t in
  58. return t.chatId
  59. }.joined(separator: ",")
  60. if let responseTopic = Nexilis.writeAndWait(message: CoreMessage_TMessageBank.getAddChatMember(groupId: self.group.id, chatId: arrayChatId, pin: u.pin)), responseTopic.isOk() {
  61. let insert = try! Database.shared.insertRecord(fmdb: fmdb, table: "GROUPZ_MEMBER", cvalues: [
  62. "group_id": self.group.id,
  63. "f_pin": u.pin,
  64. "position": "0", // 0: member, 1: Admin
  65. "user_id": u.pin,
  66. "first_name": u.firstName,
  67. "last_name": u.lastName,
  68. "msisdn": "",
  69. "thumb_id": u.thumb,
  70. "created_date": Date().currentTimeMillis()
  71. ], replace: true)
  72. if insert > 0 {
  73. if self.group.isInternal {
  74. _ = Database.shared.updateRecord(fmdb: fmdb, table: "BUDDY", cvalues: ["user_type": "23"], _where: "f_pin = '\(u.pin)'")
  75. }
  76. }
  77. result += 1
  78. }
  79. }
  80. }
  81. DispatchQueue.main.async {
  82. if self.userSelected.count == result {
  83. self.navigationController?.dismiss(animated: true, completion: {
  84. self.isDismiss?()
  85. })
  86. } else {
  87. self.showToast(message: "Server busy".localized(), seconds: 3)
  88. }
  89. }
  90. })
  91. }
  92. }
  93. // MARK: - Data source
  94. func getData(completion: @escaping ([User]) -> ()) {
  95. DispatchQueue.global().async {
  96. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  97. var r: [User] = []
  98. var query = "SELECT f_pin, first_name, last_name, image_id, user_type FROM BUDDY where f_pin not in (select m.f_pin from GROUPZ_MEMBER m where m.group_id = '\(self.group.id)') and official_account = '0' order by 2 collate nocase asc"
  99. if self.isContactCenterInvite {
  100. query = "SELECT f_pin, first_name, last_name, image_id, user_type FROM BUDDY where f_pin not in (select m.f_pin from GROUPZ_MEMBER m where m.group_id = '\(self.group.id)') and user_type = '23' and official_account = '0' order by 2 collate nocase asc"
  101. }
  102. if let cursorData = Database.shared.getRecords(fmdb: fmdb, query: query) {
  103. while cursorData.next() {
  104. let user = User(pin: cursorData.string(forColumnIndex: 0) ?? "",
  105. firstName: cursorData.string(forColumnIndex: 1) ?? "",
  106. lastName: cursorData.string(forColumnIndex: 2) ?? "",
  107. thumb: cursorData.string(forColumnIndex: 3) ?? "")
  108. user.userType = cursorData.string(forColumnIndex: 4)
  109. if (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces) == "USR\(user.pin)" {
  110. continue
  111. }
  112. r.append(user)
  113. }
  114. cursorData.close()
  115. }
  116. completion(r)
  117. })
  118. }
  119. }
  120. func filterContentForSearchText(_ searchText: String) {
  121. fillteredUser = availableUser.filter({ d in
  122. let name = "\(d.firstName) \(d.lastName)".trimmingCharacters(in: .whitespaces)
  123. return name.lowercased().contains(searchText.lowercased())
  124. })
  125. tableView.reloadData()
  126. }
  127. // MARK: - Table view data source
  128. override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
  129. let user: User
  130. if isFilltering {
  131. user = fillteredUser[indexPath.row]
  132. } else {
  133. user = availableUser[indexPath.row]
  134. }
  135. user.isSelected = !user.isSelected
  136. tableView.reloadData()
  137. if user.isSelected {
  138. userSelected.append(user)
  139. } else {
  140. if let index = userSelected.firstIndex(of: user) {
  141. userSelected.remove(at: index)
  142. }
  143. }
  144. if userSelected.count == 1 {
  145. navigationItem.rightBarButtonItem?.isEnabled = true
  146. } else if userSelected.count == 0 {
  147. navigationItem.rightBarButtonItem?.isEnabled = false
  148. }
  149. }
  150. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  151. if isFilltering {
  152. return fillteredUser.count
  153. }
  154. return availableUser.count
  155. }
  156. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  157. let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
  158. var content = cell.defaultContentConfiguration()
  159. let user: User
  160. if isFilltering {
  161. user = fillteredUser[indexPath.row]
  162. } else {
  163. user = availableUser[indexPath.row]
  164. }
  165. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  166. getImage(name: user.thumb, placeholderImage: UIImage(named: "Profile---Purple", in: Bundle.resourceBundle(for: Nexilis.self), with: nil), isCircle: true, tableView: tableView, indexPath: indexPath) { result, isDownloaded, image in
  167. content.image = image
  168. if !result {
  169. content.imageProperties.tintColor = .mainColor
  170. }
  171. }
  172. if user.userType == "23" {
  173. content.attributedText = self.set(image: UIImage(named: "ic_internal", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " " + (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces), size: 15, y: -4)
  174. } else if user.userType == "24" {
  175. content.attributedText = self.set(image: UIImage(named: "pb_call_center", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " " + (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces), size: 15, y: -4)
  176. } else {
  177. content.text = (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces)
  178. }
  179. cell.contentConfiguration = content
  180. cell.accessoryType = user.isSelected ? .checkmark : .none
  181. return cell
  182. }
  183. }
  184. extension GroupMemberViewController: UISearchControllerDelegate, UISearchBarDelegate, UISearchResultsUpdating {
  185. func updateSearchResults(for searchController: UISearchController) {
  186. filterContentForSearchText(searchController.searchBar.text!.trimmingCharacters(in: .whitespacesAndNewlines))
  187. }
  188. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat, colorText: UIColor = UIColor.black) -> NSAttributedString {
  189. let attachment = NSTextAttachment()
  190. attachment.image = image
  191. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  192. let attachmentStr = NSAttributedString(attachment: attachment)
  193. let mutableAttributedString = NSMutableAttributedString()
  194. mutableAttributedString.append(attachmentStr)
  195. let attributedStringColor = [NSAttributedString.Key.foregroundColor : colorText]
  196. let textString = NSAttributedString(string: text, attributes: attributedStringColor)
  197. mutableAttributedString.append(textString)
  198. return mutableAttributedString
  199. }
  200. }