BroadcastMembersTableViewController.swift 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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!)
  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?.isEmpty ?? true
  21. }
  22. var isFilltering: Bool {
  23. return searchController.isActive && !isSearchBarEmpty
  24. }
  25. func filterContentForSearchText(_ searchText: String) {
  26. if(isGroup){
  27. if(searchText.isEmpty){
  28. fillteredData = groups
  29. }
  30. else {
  31. fillteredData = self.groups.filter { $0.name.lowercased().contains(searchText.lowercased()) }
  32. }
  33. }
  34. else {
  35. if(searchText.isEmpty){
  36. fillteredData = contacts
  37. }
  38. else {
  39. fillteredData = self.contacts.filter { $0.fullName.lowercased().contains(searchText.lowercased()) }
  40. }
  41. }
  42. tableView.reloadData()
  43. }
  44. override func viewDidLoad() {
  45. super.viewDidLoad()
  46. searchController = UISearchController(searchResultsController: nil)
  47. searchController.delegate = self
  48. searchController.searchResultsUpdater = self
  49. searchController.searchBar.autocapitalizationType = .none
  50. searchController.searchBar.delegate = self
  51. searchController.searchBar.barTintColor = .secondaryColor
  52. searchController.searchBar.searchTextField.backgroundColor = .secondaryColor
  53. searchController.obscuresBackgroundDuringPresentation = false
  54. navigationItem.searchController = searchController
  55. navigationItem.hidesSearchBarWhenScrolling = false
  56. let buttonAddFriend = UIBarButtonItem(image: UIImage(systemName: "plus", withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular, scale: .default)), style: .plain, target: self, action: #selector(addFriend(sender:)))
  57. navigationItem.rightBarButtonItem = buttonAddFriend
  58. DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
  59. self.getData()
  60. })
  61. // Uncomment the following line to preserve selection between presentations
  62. // self.clearsSelectionOnViewWillAppear = false
  63. // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
  64. // self.navigationItem.rightBarButtonItem = self.editButtonItem
  65. }
  66. @objc func addFriend(sender: UIBarButtonItem) {
  67. let controller = AppStoryBoard.Palio.instance.instantiateViewController(identifier: "addFriendNav") as! UINavigationController
  68. if let vc = controller.viewControllers.first as? AddFriendTableViewController {
  69. vc.isDismiss = {
  70. self.contacts.removeAll()
  71. self.getContacts {
  72. DispatchQueue.main.async {
  73. self.tableView.reloadData()
  74. }
  75. }
  76. }
  77. }
  78. self.navigationController?.present(controller, animated: true, completion: nil)
  79. }
  80. override func viewWillAppear(_ animated: Bool) {
  81. pullBuddy()
  82. }
  83. @objc func onReload(notification: NSNotification) {
  84. getData()
  85. }
  86. // MARK: - Table view data source
  87. func getData() {
  88. contacts.removeAll()
  89. groups.removeAll()
  90. getContacts {
  91. DispatchQueue.main.async {
  92. self.tableView.reloadData()
  93. }
  94. }
  95. getGroups { g in
  96. self.groups.append(contentsOf: g)
  97. DispatchQueue.main.async {
  98. self.tableView.reloadData()
  99. }
  100. }
  101. }
  102. private func getContacts(completion: @escaping ()->()) {
  103. DispatchQueue.global().async {
  104. Database.shared.database?.inTransaction({ (fmdb, rollback) in
  105. do {
  106. 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") {
  107. while cursorData.next() {
  108. let user = User(pin: cursorData.string(forColumnIndex: 0) ?? "",
  109. firstName: cursorData.string(forColumnIndex: 1) ?? "",
  110. lastName: cursorData.string(forColumnIndex: 2) ?? "",
  111. thumb: cursorData.string(forColumnIndex: 3) ?? "",
  112. userType: cursorData.string(forColumnIndex: 5) ?? "")
  113. if (user.firstName + " " + user.lastName).trimmingCharacters(in: .whitespaces) == "USR\(user.pin)" {
  114. continue
  115. }
  116. user.official = cursorData.string(forColumnIndex: 4) ?? ""
  117. if(!self.existing.contains(user.pin)){
  118. self.contacts.append(user)
  119. }
  120. }
  121. cursorData.close()
  122. }
  123. } catch {
  124. rollback.pointee = true
  125. print(error)
  126. }
  127. completion()
  128. })
  129. }
  130. }
  131. private func getGroupRecursive(fmdb: FMDatabase, id: String = "", parent: String = "") -> [Group] {
  132. var data: [Group] = []
  133. 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 "
  134. if id.isEmpty {
  135. query += "g.parent = '\(parent)'"
  136. } else {
  137. query += "g.group_id = '\(id)'"
  138. }
  139. if let cursor = Database.shared.getRecords(fmdb: fmdb, query: query) {
  140. while cursor.next() {
  141. let group = Group(
  142. id: cursor.string(forColumnIndex: 0) ?? "",
  143. name: cursor.string(forColumnIndex: 1) ?? "",
  144. profile: cursor.string(forColumnIndex: 2) ?? "",
  145. quote: cursor.string(forColumnIndex: 3) ?? "",
  146. by: cursor.string(forColumnIndex: 4) ?? "",
  147. date: cursor.string(forColumnIndex: 5) ?? "",
  148. parent: cursor.string(forColumnIndex: 6) ?? "",
  149. chatId: "",
  150. groupType: cursor.string(forColumnIndex: 7) ?? "",
  151. isOpen: cursor.string(forColumnIndex: 8) ?? "",
  152. official: cursor.string(forColumnIndex: 9) ?? "",
  153. isEducation: cursor.string(forColumnIndex: 10) ?? "")
  154. // if group.chatId.isEmpty {
  155. // 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)
  156. // group.childs.append(lounge)
  157. // }
  158. //
  159. // if let topicCursor = Database.shared.getRecords(fmdb: fmdb, query: "select chat_id, title, thumb from DISCUSSION_FORUM where group_id = '\(group.id)'") {
  160. // while topicCursor.next() {
  161. // let topic = Group(id: group.id,
  162. // name: topicCursor.string(forColumnIndex: 1) ?? "",
  163. // profile: topicCursor.string(forColumnIndex: 2) ?? "",
  164. // quote: group.quote,
  165. // by: group.by,
  166. // date: group.date,
  167. // parent: group.id,
  168. // chatId: topicCursor.string(forColumnIndex: 0) ?? "",
  169. // groupType: group.groupType,
  170. // isOpen: group.isOpen,
  171. // official: group.official,
  172. // isEducation: group.isEducation)
  173. // group.childs.append(topic)
  174. // }
  175. // topicCursor.close()
  176. // }
  177. //
  178. // if !group.id.isEmpty {
  179. // if group.official == "1" {
  180. // let idMe = UserDefaults.standard.string(forKey: "me") as String?
  181. // if let cursorUser = Database.shared.getRecords(fmdb: fmdb, query: "SELECT user_type FROM BUDDY where f_pin='\(idMe!)'"), cursorUser.next() {
  182. // if cursorUser.string(forColumnIndex: 0) == "23" || cursorUser.string(forColumnIndex: 0) == "24" {
  183. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  184. // }
  185. // cursorUser.close()
  186. // }
  187. // } else if group.official != "1"{
  188. // group.childs.append(contentsOf: getGroupRecursive(fmdb: fmdb, parent: group.id))
  189. // }
  190. // }
  191. if(!self.existing.contains(group.id)){
  192. data.append(group)
  193. }
  194. }
  195. cursor.close()
  196. }
  197. return data
  198. }
  199. private func getGroups(id: String = "", parent: String = "", completion: @escaping ([Group]) -> ()) {
  200. DispatchQueue.global().async {
  201. Database.shared.database?.inTransaction({ fmdb, rollback in
  202. completion(self.getGroupRecursive(fmdb: fmdb, id: id, parent: parent))
  203. })
  204. }
  205. }
  206. private func pullBuddy() {
  207. if let me = UserDefaults.standard.string(forKey: "me") {
  208. DispatchQueue.global().async {
  209. let _ = Nexilis.write(message: CoreMessage_TMessageBank.getBatchBuddiesInfos(p_f_pin: me, last_update: 0))
  210. }
  211. }
  212. }
  213. override func numberOfSections(in tableView: UITableView) -> Int {
  214. // #warning Incomplete implementation, return the number of sections
  215. return 1
  216. }
  217. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  218. // #warning Incomplete implementation, return the number of rows
  219. if(isGroup){
  220. if(isFilltering){
  221. return fillteredData.count
  222. }
  223. return groups.count
  224. }
  225. else {
  226. if(isFilltering){
  227. return fillteredData.count
  228. }
  229. return contacts.count
  230. }
  231. }
  232. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  233. var cell: UITableViewCell!
  234. if(isGroup) {
  235. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierGroup", for: indexPath)
  236. var content = cell.defaultContentConfiguration()
  237. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  238. let group: Group
  239. if isFilltering {
  240. group = fillteredData[indexPath.row] as! Group
  241. } else {
  242. group = groups[indexPath.row]
  243. }
  244. content.text = group.name
  245. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  246. 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
  247. content.image = image
  248. }
  249. cell.contentConfiguration = content
  250. cell.tag = indexPath.row
  251. }
  252. else {
  253. cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifierContact", for: indexPath)
  254. var content = cell.defaultContentConfiguration()
  255. let data: User
  256. if isFilltering {
  257. data = fillteredData[indexPath.row] as! User
  258. } else {
  259. data = contacts[indexPath.row]
  260. }
  261. content.imageProperties.maximumSize = CGSize(width: 40, height: 40)
  262. 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
  263. content.image = image
  264. })
  265. if (data.official == "1") {
  266. 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)
  267. }
  268. else if data.userType == "23" {
  269. content.attributedText = self.set(image: UIImage(named: "ic_internal", in: Bundle.resourceBundle(for: Nexilis.self), with: nil)!, with: " \(data.fullName)", size: 15, y: -4)
  270. } else if data.userType == "24" {
  271. 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)
  272. }
  273. else {
  274. content.text = data.fullName
  275. }
  276. content.textProperties.font = UIFont.systemFont(ofSize: 14)
  277. cell.contentConfiguration = content
  278. cell.tag = indexPath.row
  279. }
  280. return cell
  281. }
  282. func set(image: UIImage, with text: String, size: CGFloat, y: CGFloat) -> NSAttributedString {
  283. let attachment = NSTextAttachment()
  284. attachment.image = image
  285. attachment.bounds = CGRect(x: 0, y: y, width: size, height: size)
  286. let attachmentStr = NSAttributedString(attachment: attachment)
  287. let mutableAttributedString = NSMutableAttributedString()
  288. mutableAttributedString.append(attachmentStr)
  289. let textString = NSAttributedString(string: text)
  290. mutableAttributedString.append(textString)
  291. return mutableAttributedString
  292. }
  293. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  294. let cell = sender as! UITableViewCell
  295. if let destination = segue.destination as? BroadcastViewController {
  296. if(isGroup){
  297. if(isFilltering){
  298. destination.groups.append(fillteredData[cell.tag] as! Group)
  299. }
  300. else {
  301. destination.groups.append(groups[cell.tag])
  302. }
  303. }
  304. else {
  305. if(isFilltering){
  306. destination.contacts.append(fillteredData[cell.tag] as! User)
  307. }
  308. else {
  309. destination.contacts.append(contacts[cell.tag])
  310. }
  311. }
  312. print("GROUPS")
  313. print(destination.groups)
  314. print("CONTACTS")
  315. print(destination.contacts)
  316. destination.memberTable.reloadData()
  317. }
  318. }
  319. /*
  320. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  321. let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
  322. // Configure the cell...
  323. return cell
  324. }
  325. */
  326. /*
  327. // Override to support conditional editing of the table view.
  328. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
  329. // Return false if you do not want the specified item to be editable.
  330. return true
  331. }
  332. */
  333. /*
  334. // Override to support editing the table view.
  335. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
  336. if editingStyle == .delete {
  337. // Delete the row from the data source
  338. tableView.deleteRows(at: [indexPath], with: .fade)
  339. } else if editingStyle == .insert {
  340. // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
  341. }
  342. }
  343. */
  344. /*
  345. // Override to support rearranging the table view.
  346. override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
  347. }
  348. */
  349. /*
  350. // Override to support conditional rearranging of the table view.
  351. override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
  352. // Return false if you do not want the item to be re-orderable.
  353. return true
  354. }
  355. */
  356. /*
  357. // MARK: - Navigation
  358. // In a storyboard-based application, you will often want to do a little preparation before navigation
  359. override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
  360. // Get the new view controller using segue.destination.
  361. // Pass the selected object to the new view controller.
  362. }
  363. */
  364. }