// // CommentsViewController.swift // GMERemittance // // Created by Fm-user on 1/16/18. // Copyright © 2018 Gobal Money Express Co. Ltd. All rights reserved. // import UIKit //import ReadMoreTextView class CommentsViewController: UIViewController { private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView() var socialfeedviewmodel: SocialFeedViewModel? var tappedIndex: Int? var feedIdFromNotification: String? var tappedCommentIndex: Int! //To keep track of comment that will be selected to edit or delete var commentInputText: String! var fromNotification: Int? private var checkDialog = 0 @IBOutlet weak var commentButton: UIButton! @IBOutlet weak var contentView: UIView! @IBOutlet weak var tableViewComments: UITableView!{ didSet { tableViewComments.estimatedRowHeight = 100 tableViewComments.rowHeight = UITableViewAutomaticDimension } } @IBOutlet weak var imageViewUserImageComment: UIImageView! @IBOutlet weak var viewCommentEdit: UIView! @IBOutlet weak var textFieldAddComment: UITextField! @IBOutlet weak var buttomConstraint: NSLayoutConstraint! private var movement: CGFloat = 0.0 private var expandedCells = Set() private var cell:CommentsTableViewCell? private var comments:String? private var feed: SocialFeed! private var newCommentsWillBeAppended: Bool = false private var arrayIndexPath = [IndexPath] () @IBOutlet weak var imageViewUserBottom: UIImageView! @IBOutlet weak var labelInitialBottom: UILabel! override func viewWillAppear(_ animated: Bool) { guard socialfeedviewmodel != nil else { return } setUpNetworkListener() setUpListener() setUpAnotherLoginListener(genericviewmodel: socialfeedviewmodel!) self.tableViewComments.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none) if tappedCommentIndex != nil { self.tableViewComments.scrollToRow(at: IndexPath(row: tappedCommentIndex!, section: 1), at: UITableViewScrollPosition.bottom, animated: true) } } override func viewWillDisappear(_ animated: Bool) { // socialfeedviewmodel?.resetCommentsArray() } override func viewDidLoad() { super.viewDidLoad() guard socialfeedviewmodel != nil else { return } socialfeedviewmodel?.socialFeedConnectionTimeOut.value = nil /** connection timeout */ socialfeedviewmodel?.socialFeedConnectionTimeOut.bind { [unowned self] in guard $0 != nil else { return } self.enableUserInteractions() self.dismissActivityIndicator(activityIndicator: self.activityIndicator) if self.fromNotification != 0{ if self.fromNotification != 0{ if self.checkDialog == 0{ self.checkDialog = self.checkDialog+1 self.popUpMessage(value: 20) } } } } socialfeedviewmodel?.resetCommentsArray() if tappedIndex != nil { setUpNavBar(id: 5, title: "") feed = socialfeedviewmodel!.getSocialFeedAt(index: tappedIndex!) disableUserInteractions() showActivityIndicator(activityIndicator: activityIndicator) socialfeedviewmodel!.fetchAllCommentsFor(feedId: feed.id, loadMore: false) } else if feedIdFromNotification != nil { setUpNavBar(id: 300, title: "Comments") if !Reachability.isConnectedToNetwork() { commentButton.isUserInteractionEnabled = false self.popUpMessage(value: 15) } else { disableUserInteractions() showActivityIndicator(activityIndicator: self.activityIndicator) socialfeedviewmodel!.fetchFeedWithId(feedId: feedIdFromNotification!) } } textFieldAddComment.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(clearKeyboard)) view.addGestureRecognizer(tap) self.tableViewComments.tableFooterView = UIView() labelInitialBottom.isHidden = false labelInitialBottom.backgroundColor = UIColor(hex: 0x2e3192) labelInitialBottom.layer.cornerRadius = labelInitialBottom.frame.height / 2 labelInitialBottom.text = getFirstName().prefix(1).uppercased() let userDpString = UserDefaults.standard.object(forKey: "com.gmeremit.dpUrl") as? String if let userDpUrl = URL(string: userDpString!) { imageViewUserBottom.isHidden = false imageViewUserBottom.sd_setImage(with: userDpUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) imageViewUserBottom.layer.cornerRadius = imageViewUserBottom.frame.height/2 labelInitialBottom.isHidden = true } } func setUpNetworkListener() { socialfeedviewmodel!.internetConnection.value = nil socialfeedviewmodel!.internetConnection.bind { [unowned self] in guard $0 != nil else { return } print("%%%%%%%%%%%") self.enableUserInteractions() self.dismissActivityIndicator(activityIndicator: self.activityIndicator) self.popUpMessage(value: 15) } } func setUpListener() { socialfeedviewmodel!.socialFeedsRxValue.bind { [weak self] in guard $0 != nil else { return } self?.enableUserInteractions() if self?.activityIndicator != nil { if (self?.activityIndicator)!.isAnimating { self?.dismissActivityIndicator(activityIndicator: (self?.activityIndicator)!) } } guard $0 != 0 else { if self?.checkDialog == 0{ self?.checkDialog = (self?.checkDialog)!+1 //self?.popUpMessageError(value: 19, message: (self?.socialfeedviewmodel!.getErrorMessage())!) } self?.socialfeedviewmodel!.socialFeedsRxValue.value = nil self?.commentButton.isUserInteractionEnabled = false self?.textFieldAddComment.isUserInteractionEnabled = false return } switch $0 { case socialWallCode.likeUnlikePost.rawValue?: if self?.tappedIndex != nil { self?.socialfeedviewmodel!.updateSocialFeedArrayLikeNumber(atIndex: (self?.tappedIndex)!) } else { self?.socialfeedviewmodel!.updateParticularFeedWithUpdatedLikeNumber() } self?.tableViewComments.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .none) case socialWallCode.fetchComments.rawValue?: // self?.tableViewComments.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none) // self?.tableViewComments.reloadSections(NSIndexSet(index: 2) as IndexSet, with: .none) let count = self?.socialfeedviewmodel!.getCommentsCount() if count! > 0 { if (self?.newCommentsWillBeAppended)! { self?.arrayIndexPath.removeAll() self?.tableViewComments.beginUpdates() let currentCount = self?.socialfeedviewmodel!.getCurrentlyFetchedCommentCount() for i in 0...(self?.socialfeedviewmodel!.getCurrentlyFetchedCommentCount())!-1 { self?.arrayIndexPath.append(IndexPath.init(row: count! - currentCount! + i, section: 1)) } self?.tableViewComments.insertRows(at: (self?.arrayIndexPath)!, with: .automatic) self?.tableViewComments.endUpdates() } else { self?.tableViewComments.reloadSections(NSIndexSet(index: 1) as IndexSet, with: .none) self?.tableViewComments.reloadSections(NSIndexSet(index: 2) as IndexSet, with: .none) } } case socialWallCode.deleteComment.rawValue?: self?.socialfeedviewmodel!.removeComment(atIndex: (self?.tappedCommentIndex)!) if self?.tappedIndex != nil { self?.socialfeedviewmodel!.updateSocialFeedArrayCommentNumber(atIndex: (self?.tappedIndex)!, increase: false) } else { self?.socialfeedviewmodel!.updateParticularFeedWithDecreasedCommentNumber() } self?.tableViewComments.deleteRows(at: [IndexPath(item: (self?.tappedCommentIndex)!, section: 1)], with: .automatic) self?.tableViewComments.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .none) case socialWallCode.createUpdateComment.rawValue?: if self?.tappedIndex != nil { self?.socialfeedviewmodel!.updateSocialFeedArrayCommentNumber(atIndex: (self?.tappedIndex)!, increase: true) } else { self?.socialfeedviewmodel!.updateParticularFeedWithIncreasedCommentNumber() } self?.textFieldAddComment.text = "" self?.tableViewComments.beginUpdates() self?.tableViewComments.insertRows(at: [IndexPath.init(row: 0, section: 1)], with: .automatic) self?.tableViewComments.endUpdates() self?.tableViewComments.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .none) self?.tableViewComments.scrollToRow(at: IndexPath(row: 0, section: 1), at: UITableViewScrollPosition.bottom, animated: true) case socialWallCode.fetchParticularPost.rawValue?: self?.feed = self?.socialfeedviewmodel!.getParticularFeed() self?.tableViewComments.reloadData() self?.socialfeedviewmodel!.fetchAllCommentsFor(feedId: (self?.feed.id)!, loadMore: false) default: return } self?.socialfeedviewmodel!.socialFeedsRxValue.value = nil } } @objc func keyboardWillShow(notification: NSNotification) { let userInfo = notification.userInfo var keyboardFrame:CGRect = (userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue keyboardFrame = self.view.convert(keyboardFrame, from: nil) movement = (keyboardFrame.size.height) UIView.animate(withDuration: 0.3, animations: { self.viewCommentEdit.frame = self.viewCommentEdit.frame.offsetBy(dx: 0, dy: self.movement * -1.0) // self.tableViewComments.frame = self.tableViewComments.frame.offsetBy(dx: 0, dy: self.movement * -1.0) self.tableViewComments.contentInset = UIEdgeInsetsMake(0.0, 0.0, self.movement, 0.0) }) } @objc func keyboardWillHide(notification: NSNotification){ UIView.animate(withDuration: 0.3, animations: { self.viewCommentEdit.frame = self.viewCommentEdit.frame.offsetBy(dx: 0, dy: self.movement) // self.tableViewComments.frame = self.tableViewComments.frame.offsetBy(dx: 0, dy: self.movement) self.tableViewComments.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) }) } @IBAction func commentAddButton(_ sender: Any) { disableUserInteractions() showActivityIndicator(activityIndicator: activityIndicator) textFieldAddComment.resignFirstResponder() socialfeedviewmodel!.createCommentFor(feedId: feed.id) } @objc func clearKeyboard() { textFieldAddComment?.resignFirstResponder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { switch segue.identifier { case "editComment"?: let editCommentViewController = segue.destination as! EditCommentViewController editCommentViewController.commentIndex = tappedCommentIndex editCommentViewController.socialfeedviewmodel = socialfeedviewmodel! if tappedIndex != nil { editCommentViewController.feedIndex = tappedIndex! } case "showLikedByFromComments"?: let likedByViewController = segue.destination as! LikesViewController likedByViewController.socialfeedviewmodel = socialfeedviewmodel if tappedIndex != nil { likedByViewController.tappedIndex = tappedIndex } default: return } } } extension CommentsViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { commentInputText = (textField.text! as NSString).replacingCharacters(in: range, with: string) socialfeedviewmodel?.updateCommentText(text: commentInputText) return true } } extension CommentsViewController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 3 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch section { case 0: if feed != nil { return 1 } return 0 case 1: if (socialfeedviewmodel?.getAllComments().count)! > 0{ return socialfeedviewmodel!.getAllComments().count } return 0 case 2: return 1 default: return 0 } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.section { case 0: cell = tableView.dequeueReusableCell(withIdentifier: "statusCell", for: indexPath) as? CommentsTableViewCell cell!.imageViewUser.layer.cornerRadius = cell!.imageViewUser.frame.height / 2 /* To show changes in comment number and likes when likes/comments are updated*/ if tappedIndex != nil { feed = socialfeedviewmodel!.getSocialFeedAt(index: tappedIndex!) } else { feed = socialfeedviewmodel!.getParticularFeed() } cell?.labelInitialTop.isHidden = false cell?.labelInitialTop.backgroundColor = UIColor(hex: 0x2e3192) cell?.labelInitialTop.layer.cornerRadius = cell!.labelInitialTop.frame.height / 2 cell?.labelInitialTop.text = feed.firstName.prefix(1).uppercased() if let userDpString = feed.userDpUrl { if let userDpUrl = URL(string: userDpString) { cell?.imageViewUser.isHidden = false cell?.imageViewUser.sd_setImage(with: userDpUrl, placeholderImage: #imageLiteral(resourceName: "gme-logo"), options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) cell?.labelInitialTop.isHidden = true } } cell?.labelUserName.text = socialfeedviewmodel!.getFullName(feed: feed) cell?.labelTimeAgo.text = feed.agoDate if let feedText = feed.feedText { cell?.labelFeedContent.text = feedText } if let feedImageString = feed.feedImage { if let feedImageUrl = URL(string: feedImageString) { cell?.imageViewFeed.sd_setImage(with: feedImageUrl, placeholderImage: #imageLiteral(resourceName: "gme-logo"), options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) cell?.imageHeightConstraint.constant = view.frame.width } } else { cell?.imageHeightConstraint.constant = 0 } if feed.liked { cell?.buttonLikeStatus.setImage(UIImage(named:"ic_heartfull"), for: UIControlState.normal) } else { cell?.buttonLikeStatus.setImage(UIImage(named:"ic_heart"), for: UIControlState.normal) } cell?.buttonLikeStatus?.addTarget(self, action: #selector(toggleLike(_:)), for: .touchUpInside) //Display total number of LIKES if feed.totalLike > 1 { cell?.buttonLikes.setTitle("\(feed.totalLike) Likes", for:UIControlState.normal) } else { cell?.buttonLikes.setTitle("\(feed.totalLike) Like", for:UIControlState.normal) } if feed.totalLike > 0 { cell?.buttonLikes?.addTarget(self, action: #selector(showLikes(_:)), for: .touchUpInside) } if feed.totalComment > 1 { cell?.buttonComments.setTitle(" \(feed.totalComment) Comments", for:UIControlState.normal) } else { cell?.buttonComments.setTitle(" \(feed.totalComment) Comment", for:UIControlState.normal) } return cell! case 1: cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as? CommentsTableViewCell let comment = socialfeedviewmodel!.getCommentAt(index: indexPath.row) cell!.labelName.text = comment.userName cell!.labelComment.text = comment.userComment cell!.labelTime.text = comment.agoDate cell!.imageViewComment.layer.cornerRadius = cell!.imageViewComment.frame.height / 2 cell!.labelUserNameInitial.isHidden = false cell!.labelUserNameInitial.backgroundColor = UIColor(hex: 0x2e3192) cell!.labelUserNameInitial.layer.cornerRadius = cell!.labelUserNameInitial.frame.height / 2 cell!.labelUserNameInitial.text = comment.userName.prefix(1).uppercased() if let userDpString = comment.userDpUrl { if let userDpUrl = URL(string: userDpString) { cell!.imageViewComment.isHidden = false cell!.imageViewComment.sd_setImage(with: userDpUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) } cell!.labelUserNameInitial.isHidden = true } // if let userimageUrl = socialfeedviewmodel!.getCommentAt(index: indexPath.row).userDpUrl { // cell?.imageViewComment.sd_setImage(with: URL(string: userimageUrl), placeholderImage: #imageLiteral(resourceName: "gme-logo"), options: [.progressiveDownload,.scaleDownLargeImages], completed: nil) // } return cell! case 2: cell = (tableView.dequeueReusableCell(withIdentifier: "loadMoreCell", for: indexPath) as! CommentsTableViewCell) cell!.buttonLoadMore.addTarget(self, action: #selector(loadMore(_:)), for: .touchUpInside) if !socialfeedviewmodel!.commentsRemaining() { cell!.buttonLoadMore.isHidden = true } else { cell!.buttonLoadMore.isHidden = false } return cell! default: return cell! } } @objc func loadMore(_ sender: TableViewCell) { disableUserInteractions() showActivityIndicator(activityIndicator: activityIndicator) newCommentsWillBeAppended = true socialfeedviewmodel!.fetchAllCommentsFor(feedId: feed.id, loadMore: true) } @objc func showLikes(_ sender: CommentsTableViewCell) { textFieldAddComment.resignFirstResponder() guard Reachability.isConnectedToNetwork() else { self.popUpMessage(value: 15) return } self.performSegue(withIdentifier: "showLikedByFromComments", sender: nil) } /* LIKE OR DISLIKE A POST WHEN TAPPPED */ @objc func toggleLike(_ sender: TableViewCell) { if tappedIndex != nil { // feed = socialfeedviewmodel?.getSocialFeedAt(index: tappedIndex!) socialfeedviewmodel!.likeDislikePost(feedId: feed.id, liked: feed.liked) } else { // feed = socialfeedviewmodel?.getParticularFeed() socialfeedviewmodel!.likeDislikePost(feedId: feed.id, liked: feed.liked) } } func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? { switch indexPath.section { case 1: let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in let alert = UIAlertController(title: "Are you sure you want to delete?", message: "", preferredStyle: .alert) let cancelAction = UIAlertAction(title: "No", style: .destructive) { (action) -> Void in alert.dismiss(animated: true, completion: nil) } let deleteAction = UIAlertAction(title: "Yes", style: .destructive) { (action) -> Void in alert.dismiss(animated: true, completion: nil) let feedId = self.feed.id //self.socialfeedviewmodel!.getSocialFeedAt(index: self.tappedIndex!).id let commentId = self.socialfeedviewmodel!.getCommentAt(index: indexPath.row).commentId self.tappedCommentIndex = indexPath.row self.disableUserInteractions() self.showActivityIndicator(activityIndicator: self.activityIndicator) self.socialfeedviewmodel!.removeComment(feedId: feedId, commentId: commentId!) } alert.addAction(cancelAction) alert.addAction(deleteAction) self.present(alert, animated: true, completion: nil) } let edit = UITableViewRowAction(style: .normal, title: "Edit") { (action, indexPath) in self.tappedCommentIndex = indexPath.row self.performSegue(withIdentifier: "editComment", sender: nil) } let cancel = UITableViewRowAction(style: .normal, title: "Cancel") {_,_ in } if tappedIndex != nil { if socialfeedviewmodel!.postBelongsToMe(postIndex: tappedIndex!) { if socialfeedviewmodel!.commentBelongsToMe(commentIndex: indexPath.row) { return [edit, delete] } else { return [delete, cancel] } } else if socialfeedviewmodel!.commentBelongsToMe(commentIndex: indexPath.row) { return [edit, delete] } } else { if socialfeedviewmodel!.particularPostBelongsToMe() { if socialfeedviewmodel!.commentBelongsToMe(commentIndex: indexPath.row) { return [edit, delete] } else { return [delete, cancel] } } else if socialfeedviewmodel!.commentBelongsToMe(commentIndex: indexPath.row) { return [edit, delete] } } default: return [] } return [] } // private func tableView(_ tableView: UITableView, willDisplay cell: CommentsTableViewCell, forRowAt indexPath: IndexPath) { // // switch indexPath.section { // case 1: // let readMoreTextView = cell.contentView.viewWithTag(1) as? ReadMoreTextView // readMoreTextView?.onSizeChange = { [unowned tableView, unowned self] r in // let point = tableView.convert(r.bounds.origin, from: r) // guard let indexPath = tableView.indexPathForRow(at: point) else { return } // if r.shouldTrim { // self.expandedCells.remove(indexPath.row) // } else { // self.expandedCells.insert(indexPath.row) // } // self.tableViewComments.reloadData() // } // default: // break // } // // } // func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // // switch indexPath.section { // case 0: // print("section") // case 1: // print("coment") // let cell = tableView.cellForRow(at: indexPath)! // let readMoreTextView = cell.contentView.viewWithTag(1) as? ReadMoreTextView // readMoreTextView?.shouldTrim = !(readMoreTextView?.shouldTrim)! // default: break // } // // } }