Advertisement
Dillon25

Untitled

Jul 15th, 2020
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 55.36 KB | None | 0 0
  1. //
  2. //  CommentVC.swift
  3. //  VolumeiOS
  4. //
  5. //  Created by Dillon Davis on 6/13/20.
  6. //  Copyright © 2020 Dillon Davis. All rights reserved.
  7. //
  8.  
  9. import Foundation
  10. import UIKit
  11.  
  12. struct CommentStruct {
  13.     static var isSelected:Bool? = false
  14.     static var subCommentReplySelected:Bool? = false
  15.     static var parent_id:String?
  16.    
  17.     func updateIsSelected(newBool: Bool) {
  18.         CommentStruct.self.isSelected = newBool
  19.     }
  20.    
  21.     func updateParentId(newString: String) {
  22.         CommentStruct.self.parent_id = newString
  23.     }
  24.    
  25.     func updatesubReplyIsSelected(newBool: Bool) {
  26.         CommentStruct.self.subCommentReplySelected = newBool
  27.     }
  28.    
  29. }
  30.  
  31. protocol TableViewSubCommentDelegate {
  32.     func didSendSubComment(parent_id:String)
  33. }
  34.  
  35. protocol TableViewDelegate: class {
  36.     func didSendSubComment()
  37. }
  38.  
  39.  
  40.  
  41. class CommentVC: UIViewController, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UITextViewDelegate, UpdateTableView {
  42.     func updateTableView(bool: Bool) {
  43.          if bool == true {
  44.             UIView.performWithoutAnimation {
  45.                self.myTableView.beginUpdates()
  46.                self.myTableView.endUpdates()
  47.             }
  48.         }
  49.     }
  50.    
  51.    
  52.     private var myTableView:UITableView!
  53.     var textField = UITextField()
  54.     var bottomConstraint:NSLayoutConstraint?
  55.     var profile = SessionManager.shared.profile
  56.     var username:String?
  57.     var imageLoader:DownloadImage?
  58.     var comments:[CommentViewModel] = []
  59.     var sub_comments:[CommentViewModel] = []
  60.     var textViewHeight = CGFloat()
  61.     let countLabel = UILabel()
  62.     let textViewView = UIView()
  63.     let sendBtn = UIButton()
  64.     var tap: UITapGestureRecognizer?
  65.     let comment = CommentStruct()
  66.     var parent_id:String?
  67.     var reply:Bool = false
  68.     var subReply:Bool = false
  69.     var delegate:TableViewSubCommentDelegate?
  70.     weak var delegate2:TableViewDelegate?
  71.     var usernameReply:String?
  72.     var index:IndexPath?
  73.     var replyingCommentCell: CommentCell?
  74.    
  75.     lazy var textView:UITextView = {
  76.         let tv = UITextView()
  77.         tv.isScrollEnabled = false
  78.         tv.text = "Enter Comment"
  79.         tv.textColor = UIColor.lightGray
  80.         tv.sizeToFit()
  81.         tv.returnKeyType = UIReturnKeyType.default
  82.         tv.layer.cornerRadius = 4
  83.         tv.layer.borderColor = UIColor.lightGray.cgColor
  84.         tv.layer.borderWidth = 0.5
  85.         tv.keyboardType = UIKeyboardType.default
  86.         tv.backgroundColor = UIColor.white
  87.         tv.textContainer.maximumNumberOfLines = 0
  88.         tv.textContainer.lineBreakMode = .byCharWrapping
  89.         tv.font = UIFont(name: "GillSans", size: 18)
  90.         return tv
  91.     }()
  92.    
  93.     override func viewDidLoad() {
  94.         view.backgroundColor = UIColor.white
  95.         navigationController?.isToolbarHidden = true
  96.         getUser()
  97.         self.textView.delegate = self
  98.         view.addSubview(self.textViewView)
  99.         view.bringSubviewToFront(self.textViewView)
  100.         textViewView.addSubview(textView)
  101.         textViewView.addSubview(sendBtn)
  102.         sendBtn.isEnabled = false
  103.         createViewForTextView()
  104.         setupTextViewConstraints()
  105.         createSendButton()
  106.         addTableView()
  107.         loadComments()
  108.        
  109.        
  110.         view.isUserInteractionEnabled = true
  111.         tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard))
  112.  
  113.         if let tap = tap {
  114.         view.addGestureRecognizer(tap)
  115.         }
  116.         NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification), name: UIResponder.keyboardWillShowNotification, object: nil)
  117.        
  118.         NotificationCenter.default.addObserver(self, selector: #selector(handleKeyBoardNotification), name: UIResponder.keyboardWillHideNotification, object: nil)
  119.     }
  120.    
  121.     func getUser() {
  122.         if let id = profile?.sub {
  123.             print("profile?.sub id \(profile?.sub)")
  124.             GetUsersById(id: id).getAllPosts {
  125.                 self.username = $0[0].username
  126.                 print("self.username \(self.username)")
  127.             }
  128.         } else {
  129.             print("profile?.sub \(profile?.sub)")
  130.         }
  131.     }
  132.    
  133.    func setupCountLabel() {
  134.         countLabel.textColor = UIColor.black
  135.         countLabel.textAlignment = .center
  136.         countLabel.layer.cornerRadius = 5
  137.         countLabel.layer.borderWidth = 1.0
  138.         countLabel.backgroundColor = UIColor.white
  139.         countLabel.layer.borderColor = UIColor.lightGray.cgColor
  140.         view.addSubview(countLabel)
  141.         countLabel.translatesAutoresizingMaskIntoConstraints = false
  142.         countLabel.widthAnchor.constraint(equalToConstant: 50).isActive = true
  143.         countLabel.heightAnchor.constraint(equalToConstant: 20).isActive = true
  144.         countLabel.bottomAnchor.constraint(equalTo: textView.topAnchor).isActive = true
  145.         countLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  146.        
  147.     }
  148.    
  149.    
  150.     func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
  151.         if CommentStruct.isSelected! && reply {
  152.             textView.text = nil
  153.             textView.textColor = UIColor.black
  154.             reply = false
  155.         }
  156.         if CommentStruct.subCommentReplySelected! && subReply {
  157.             textView.text = nil
  158.             textView.textColor = UIColor.black
  159.             subReply = false
  160.         }
  161.         if text == "\n" {
  162.             textView.resignFirstResponder()
  163.             return false
  164.         }
  165.         countLabel.text = "\(textView.text.count)"
  166.         return textView.text.count + (text.count - range.length) <= 250
  167.     }
  168.    
  169.     func textViewDidBeginEditing(_ textView: UITextView) {
  170.             textView.text = nil
  171.             textView.textColor = UIColor.black
  172.     }
  173.    
  174.    
  175.    
  176.     func textViewDidChange(_ textView: UITextView) {
  177.         if textView.text == "" {
  178.             sendBtn.isEnabled = false
  179.         } else {
  180.             sendBtn.isEnabled = true
  181.         }
  182.     }
  183.    
  184.     func textViewDidEndEditing(_ textView: UITextView) {
  185.         if textView.text == "" {
  186.             textView.text = "Enter Comment"
  187.             textView.textColor = UIColor.lightGray
  188.         }
  189.     }
  190.    
  191.  
  192.     @objc func dismissKeyboard() {
  193.         textView.resignFirstResponder()
  194.         if textView.text == "Reply" && self.textView.textColor == UIColor.lightGray {
  195.             textView.text = "Enter Comment"
  196.             textView.textColor = UIColor.lightGray
  197.         }
  198.         if textView.text == "" {
  199.             textView.text = "Enter Comment"
  200.             textView.textColor = UIColor.lightGray
  201.         }
  202.         print("dismissKeyBoard")
  203.     }
  204.    
  205.     @objc func handleKeyBoardNotification(notification:NSNotification) {
  206.         if let userInfo = notification.userInfo {
  207.             let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
  208.             let isKeyBoardShowing = notification.name == UIResponder.keyboardWillShowNotification
  209.             bottomConstraint?.constant = isKeyBoardShowing ? -keyboardFrame.height : 0
  210.  
  211.             UIView.animate(withDuration: 0, delay: 0, options: UIView.AnimationOptions.curveEaseOut, animations: {
  212.                 self.view.layoutIfNeeded()
  213.             }) { (completed) in
  214.                
  215.             }
  216.         }
  217.     }
  218.    
  219.     func loadComments() {
  220.         let getComments = GETComments(id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", path: "comments")
  221.         getComments.getAllById { comments in
  222.             self.comments = comments.map { comment in
  223.                 let ret = CommentViewModel()
  224.                 ret.mainComment = comment
  225.        
  226.                 return ret
  227.             }
  228.             self.myTableView.reloadData()
  229.         }
  230.     }
  231.    
  232.  
  233.    
  234.     func addTableView() {
  235.        
  236.         self.myTableView = UITableView()
  237.        
  238.        
  239.         self.myTableView?.translatesAutoresizingMaskIntoConstraints = false
  240.        
  241.         self.myTableView.frame.size.height = self.view.frame.height
  242.      
  243.         self.myTableView.frame.size.width = self.view.frame.width
  244.        
  245.        
  246.         self.myTableView.register(CommentCell.self, forCellReuseIdentifier: "MyCell")
  247.         self.myTableView.dataSource = self
  248.         self.myTableView.delegate = self
  249.         self.myTableView.isScrollEnabled = true
  250.        
  251.         myTableView.delaysContentTouches = false
  252.         self.view.addSubview(self.myTableView)
  253.        
  254.    
  255.         self.myTableView?.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
  256.        
  257.         self.myTableView?.leadingAnchor.constraint(equalTo: self.view.leadingAnchor).isActive = true
  258.        
  259.         self.myTableView?.trailingAnchor.constraint(equalTo: self.view.trailingAnchor).isActive = true
  260.        
  261.         self.myTableView.bottomAnchor.constraint(equalTo: self.textView.topAnchor).isActive = true
  262.        
  263.         self.myTableView.estimatedRowHeight = 80
  264.         self.myTableView.rowHeight = UITableView.automaticDimension
  265.        
  266.        
  267.         myTableView.layoutMargins = UIEdgeInsets.zero
  268.         myTableView.separatorInset = UIEdgeInsets.zero
  269.        
  270.        
  271.     }
  272.    
  273.  
  274.    
  275.    
  276.     func setupTextViewConstraints() {
  277.         textView.translatesAutoresizingMaskIntoConstraints = false
  278.         textView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
  279.         textView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -10).isActive = true
  280.         textView.topAnchor.constraint(equalTo: textViewView.topAnchor).isActive = true
  281.         var frame = self.textView.frame
  282.         frame.size.height = self.textView.contentSize.height
  283.         self.textView.frame = frame
  284.                
  285. }
  286.    
  287.     func createViewForTextView() {
  288.         textViewView.backgroundColor = UIColor.white
  289.         textViewView.layer.borderColor = UIColor.lightGray.cgColor
  290.         textViewView.layer.borderWidth = 1.0
  291.         textViewView.translatesAutoresizingMaskIntoConstraints = false
  292.         textViewView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
  293.         textViewView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
  294.         textViewView.heightAnchor.constraint(equalTo: textView.heightAnchor, constant: 50).isActive = true
  295.        
  296.        
  297.         bottomConstraint = textViewView.bottomAnchor.constraint(equalTo: (self.view.safeAreaLayoutGuide.bottomAnchor), constant: 0)
  298.         bottomConstraint?.isActive = true
  299.     }
  300.    
  301.     func createSendButton() {
  302.         let btnConfiguration = UIImage.SymbolConfiguration(scale: .medium)
  303.         let btnSymbolImage = UIImage(systemName: "arrowshape.turn.up.right.fill", withConfiguration: btnConfiguration)
  304.         sendBtn.setImage(btnSymbolImage, for: .normal)
  305.         sendBtn.translatesAutoresizingMaskIntoConstraints = false
  306.         sendBtn.heightAnchor.constraint(equalToConstant: 20).isActive = true
  307.         sendBtn.widthAnchor.constraint(equalToConstant: 30).isActive = true
  308.         sendBtn.trailingAnchor.constraint(equalTo: textViewView.trailingAnchor, constant: -8).isActive = true
  309.         sendBtn.bottomAnchor.constraint(equalTo: self.textViewView.bottomAnchor, constant: -15).isActive = true
  310.         sendBtn.addTarget(self, action: #selector(sendComment), for: .touchUpInside)
  311.        
  312.     }
  313.    
  314.     @objc func sendComment() {
  315.         if CommentStruct.isSelected == true {
  316.           print("true isSelected")
  317.           sendSubComment()
  318.         } else if CommentStruct.subCommentReplySelected == true {
  319.           sendSubCommentReply()
  320.         } else {
  321.           print("false not selected")
  322.           performActionSend()
  323.         }
  324.         view.endEditing(true)
  325.     }
  326.  
  327.     func sendSubComment() {
  328.         if let text = textView.text,
  329.         let username = self.username,
  330.         let user_picture = profile?.picture,
  331.         let user_id = profile?.sub,
  332.         let parent_id = parent_id {
  333.             let comment = Comment(post_id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", username: username, user_picture: user_picture.absoluteString, user_id: user_id, text: text, parent_id: parent_id)
  334.  
  335.             let postRequest = CommentPostRequest(endpoint: "sub_comment")
  336.             postRequest.save(comment) { (result) in
  337.                 switch result {
  338.                 case .success(let comment):
  339.                     let viewModel = CommentViewModel()
  340.                     self.delegate?.didSendSubComment(parent_id: parent_id)
  341.                     print("self.delegate2 \(self.delegate2)")
  342.                     print("delegate tableview \(self.delegate)")
  343.                     DispatchQueue.main.async {
  344.                        self.replyingCommentCell?.addedSubComment()
  345.                    
  346.                     self.delegate2?.didSendSubComment()
  347.                         print("self.delegate2 \(self.delegate2) main async")
  348.                     self.myTableView.reloadData()
  349.                     UIView.performWithoutAnimation {
  350.                        self.myTableView.beginUpdates()
  351.                        self.myTableView.endUpdates()
  352.                     }
  353.                 }
  354.                 case .failure(let error):
  355.                     print("An error occurred: \(error)")
  356.                 }
  357.             }
  358.         } else {
  359.             print("text \(textView.text)")
  360.             print("username \(self.username)")
  361.             print("user_picture \(profile?.picture)")
  362.             print("user_id \(profile?.sub)")
  363.             print("parent_id \(parent_id)")
  364.         }
  365.         textView.text = ""
  366.     }
  367.    
  368.    
  369.     func sendSubCommentReply() {
  370.         if let text = textView.text,
  371.         let username = self.username,
  372.         let user_picture = profile?.picture,
  373.         let user_id = profile?.sub,
  374.         let parent_id = parent_id,
  375.         let usernameReply = usernameReply {
  376.             let comment = Comment(post_id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", username: username, user_picture: user_picture.absoluteString, user_id: user_id, text:
  377.                 "Reply To @\(usernameReply): \(text)", parent_id: parent_id)
  378.            
  379.             let postRequest = CommentPostRequest(endpoint: "sub_comment")
  380.             postRequest.save(comment) { (result) in
  381.                 switch result {
  382.                 case .success(let comment):
  383.                     var viewModel = CommentViewModel()
  384.                     self.delegate?.didSendSubComment(parent_id: parent_id)
  385.                     print("delegate tableview \(self.delegate)")
  386.                     DispatchQueue.main.async {
  387.                     self.replyingCommentCell?.addedSubComment()
  388.                     self.myTableView.reloadData()
  389.                     UIView.performWithoutAnimation {
  390.                        self.myTableView.beginUpdates()
  391.                        self.myTableView.endUpdates()
  392.                     }
  393.                 }
  394.                 case .failure(let error):
  395.                     print("An error occurred: \(error)")
  396.                 }
  397.             }
  398.         } else {
  399.             print("text \(textView.text)")
  400.             print("username \(username)")
  401.             print("user_picture \(profile?.picture)")
  402.             print("user_id \(profile?.sub)")
  403.             print("parent_id \(parent_id)")
  404.         }
  405.         textView.text = ""
  406.     }
  407.    
  408.     func performActionSend() {
  409.         if let text = textView.text,
  410.         let username = username,
  411.         let user_picture = profile?.picture,
  412.         let user_id = profile?.sub {
  413.             let comment = Comment(post_id: "2d44a588-e47a-43c5-bd16-94e7073e4e14", username: username, user_picture: user_picture.absoluteString, user_id: user_id, text: text, parent_id: nil)
  414.            
  415.             let postRequest = CommentPostRequest(endpoint: "comment")
  416.             postRequest.save(comment) { (result) in
  417.                 switch result {
  418.                 case .success(let comment):
  419.                     print("the following comment has been sent: \(comment)")
  420.                    
  421.                     self.loadComments()
  422.                 case .failure(let error):
  423.                     print("An error occurred: \(error)")
  424.                 }
  425.             }
  426.         } else {
  427.             print("text \(textView.text)")
  428.             print("username \(username)")
  429.             print("user_picture \(profile?.picture)")
  430.             print("user_id \(profile?.sub)")
  431.         }
  432.         textView.text = ""
  433.     }
  434.    
  435.  
  436.     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  437.         return comments.count
  438.     }
  439.  
  440.    
  441.     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  442.         let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath as IndexPath) as! CommentCell
  443.         cell.delegate = self
  444.         cell.delegate2 = self
  445.         cell.selectionStyle = .none
  446.         cell.index = indexPath
  447.         cell.commentDelegate = self
  448.         let item = comments[indexPath.item]
  449.         cell.viewModel = item
  450.         return cell
  451.     }
  452.    
  453.    
  454. }
  455.  
  456.  
  457. extension CommentVC: CommentCellDelegate {
  458.     func didTapReplyBtn(parent_id: String, cell: CommentCell) {
  459.         if !textView.isFirstResponder {
  460.                    textView.becomeFirstResponder()
  461.                    comment.updateIsSelected(newBool: true)
  462.                    self.replyingCommentCell = cell
  463.                    reply = true
  464.                    self.parent_id = parent_id
  465.                     textView.text = nil
  466.                     if textView.text.isEmpty {
  467.  
  468.                        textView.text = "Reply"
  469.                        textView.textColor = UIColor.lightGray
  470.  
  471.                        textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
  472.                    }
  473.  
  474.                 } else {
  475.                     textView.text = nil
  476.                     textView.resignFirstResponder()
  477.                     if textView.text.isEmpty {
  478.  
  479.                         textView.text = "Enter Comment"
  480.                         textView.textColor = UIColor.lightGray
  481.          }
  482.      }
  483.    
  484.   }
  485. }
  486.  
  487.  
  488. extension CommentVC: CommentCellDelegate2 {
  489.    
  490.    
  491.     func didTapSubReplyBtn(username: String, parent_id:String, cell: CommentCell) {
  492.         if !textView.isFirstResponder {
  493.                       textView.becomeFirstResponder()
  494.                       comment.updateIsSelected(newBool: false)
  495.                       comment.updatesubReplyIsSelected(newBool: true)
  496.                       subReply = true
  497.                       self.parent_id = parent_id
  498.                       self.usernameReply = username
  499.                       self.replyingCommentCell = cell
  500.                       textView.text = nil
  501.                        if textView.text.isEmpty {
  502.                           textView.text = "Reply"
  503.                           textView.textColor = UIColor.lightGray
  504.                           textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument)
  505.                       }
  506.  
  507.                    } else {
  508.                        textView.text = nil
  509.                        textView.resignFirstResponder()
  510.                        if textView.text.isEmpty {
  511.  
  512.                            textView.text = "Enter Comment"
  513.                            textView.textColor = UIColor.lightGray
  514.             }
  515.         }
  516.        
  517.     }
  518.    
  519. }
  520.  
  521.  
  522. import Foundation
  523. import UIKit
  524. import Combine
  525.  
  526. protocol UpdateTableView: class {
  527.     func updateTableView(bool: Bool)
  528. }
  529.  
  530. protocol CommentViewDelegate: class {
  531.     func subCommentLikePressed(sender: UIButton)
  532.     func replyToSubComment(sender: UIButton)
  533.    
  534. }
  535.  
  536.  
  537.  
  538.  
  539. class CommentView: UIView {
  540.    
  541.     weak var delegate: CommentViewDelegate?
  542.    
  543.     override init(frame: CGRect) {
  544.         super.init(frame: frame)
  545.         addSubview(user_image)
  546.         addSubview(username)
  547.         addSubview(textView)
  548.         addSubview(likeBtn)
  549.         addSubview(numberOfLikes)
  550.         addSubview(replyBtn)
  551.         replyBtnConstraints()
  552.         setImageConstraints()
  553.         setUsernameConstraints()
  554.         textViewContstraints()
  555.         commentLikeBtnConstraints()
  556.         commentLikesConstraints()
  557.        
  558.     }
  559.    
  560.    
  561.     required init?(coder: NSCoder) {
  562.         fatalError("init(coder:) has not been implemented")
  563.     }
  564.    
  565.     lazy var replyBtn:UIButton = {
  566.         let btn = UIButton()
  567.         btn.setTitle("Reply", for: .normal)
  568.         btn.setTitleColor(UIColor.gray, for: .normal)
  569.         btn.titleLabel?.font = .systemFont(ofSize: 12)
  570.         btn.contentHorizontalAlignment = .left
  571.         btn.addTarget(self, action: #selector(replyToSubComment(sender:)), for: .touchUpInside)
  572.         return btn
  573.     }()
  574.    
  575.     lazy var likeBtn:UIButton = {
  576.         let btn = UIButton()
  577.         let symbol = UIImage(systemName: "heart")
  578.         btn.setImage(symbol , for: .normal)
  579.         btn.tintColor = UIColor.darkGray
  580.         btn.isUserInteractionEnabled = true
  581.         btn.addTarget(self, action: #selector(subCommentLikePressed(sender:)), for: .touchUpInside)
  582.         return btn
  583.     }()
  584.    
  585.     var numberOfLikes:UILabel = {
  586.         let label = UILabel()
  587.         label.textAlignment = .center
  588.         label.text = "0"
  589.         return label
  590.     }()
  591.    
  592.    
  593.    
  594.     lazy var textView:UITextView = {
  595.         let tv = UITextView()
  596.         tv.isScrollEnabled = false
  597.         tv.isEditable = false
  598.         tv.sizeToFit()
  599.         tv.backgroundColor = UIColor.lightGray
  600.         tv.textContainer.maximumNumberOfLines = 0
  601.         tv.textContainer.lineBreakMode = .byCharWrapping
  602.         tv.font = UIFont(name: "GillSans", size: 18)
  603.         return tv
  604.     }()
  605.    
  606.     lazy var user_image: UIImageView = {
  607.         let image = UIImageView()
  608.        
  609.         return image
  610.     }()
  611.    
  612.     lazy var username:UILabel = {
  613.         let label = UILabel()
  614.         label.textColor = UIColor.gray
  615.         label.font = UIFont.systemFont(ofSize: 14)
  616.         return label
  617.     }()
  618.    
  619.     @objc func subCommentLikePressed(sender:UIButton) {
  620.         print("delegate \(delegate)")
  621.         if let delegate = delegate {
  622.             delegate.subCommentLikePressed(sender: sender)
  623.         }
  624.     }
  625.    
  626.     @objc func replyToSubComment(sender:UIButton) {
  627.         print("delegate \(delegate)")
  628.         if let delegate = delegate {
  629.             delegate.replyToSubComment(sender: sender)
  630.         }
  631.     }
  632.    
  633.     func replyBtnConstraints() {
  634.         replyBtn.translatesAutoresizingMaskIntoConstraints = false
  635.         replyBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
  636.         replyBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
  637.         replyBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
  638.         replyBtn.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 1).isActive = true
  639.         replyBtn.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
  640.        
  641.     }
  642.    
  643.     func commentLikesConstraints() {
  644.         numberOfLikes.translatesAutoresizingMaskIntoConstraints = false
  645.         numberOfLikes.widthAnchor.constraint(equalToConstant: 60).isActive = true
  646.         numberOfLikes.heightAnchor.constraint(equalToConstant: 30).isActive = true
  647.         numberOfLikes.centerXAnchor.constraint(equalTo: likeBtn.centerXAnchor).isActive = true
  648.         numberOfLikes.topAnchor.constraint(equalTo: likeBtn.bottomAnchor, constant: -5).isActive = true
  649.     }
  650.    
  651.     func commentLikeBtnConstraints() {
  652.         likeBtn.translatesAutoresizingMaskIntoConstraints = false
  653.         likeBtn.widthAnchor.constraint(equalToConstant: 60).isActive = true
  654.         likeBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
  655.         likeBtn.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
  656.         likeBtn.topAnchor.constraint(equalTo: textView.topAnchor, constant: -5).isActive = true
  657.     }
  658.    
  659.     func setImageConstraints() {
  660.         user_image.translatesAutoresizingMaskIntoConstraints = false
  661.         user_image.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
  662.         user_image.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8).isActive = true
  663.         user_image.heightAnchor.constraint(equalToConstant: 40).isActive = true
  664.         user_image.widthAnchor.constraint(equalToConstant: 40).isActive = true
  665.        
  666.     }
  667.    
  668.     func setUsernameConstraints() {
  669.         username.translatesAutoresizingMaskIntoConstraints = false
  670.         username.topAnchor.constraint(equalTo: user_image.topAnchor, constant: 5).isActive = true
  671.         username.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
  672.         username.heightAnchor.constraint(equalToConstant: 10).isActive = true
  673.         username.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
  674.     }
  675.    
  676.     func textViewContstraints() {
  677.         textView.translatesAutoresizingMaskIntoConstraints = false
  678.         textView.topAnchor.constraint(equalTo: username.bottomAnchor, constant: 5).isActive = true
  679.         textView.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
  680.         textView.trailingAnchor.constraint(equalTo: likeBtn.leadingAnchor, constant: -3).isActive = true
  681.        
  682.     }
  683.    
  684.    
  685. }
  686.  
  687. extension UITableViewCell {
  688.     var tableView: UITableView? {
  689.         var p = self.superview
  690.         while p != nil {
  691.             if let t = p as? UITableView {
  692.                 return t
  693.             }
  694.             p = p?.superview
  695.         }
  696.         return nil
  697.     }
  698.    
  699.     func viewContentLayoutIfNeed() {
  700.         self.tableView?.beginUpdates()
  701.         self.tableView?.endUpdates()
  702.     }
  703.     func viewContentSetNeedsDisplay() {
  704.         UIView.performWithoutAnimation {
  705.             self.tableView?.beginUpdates()
  706.             self.tableView?.endUpdates()
  707.         }
  708.     }
  709. }
  710.  
  711. protocol CommentCellDelegate {
  712.     func didTapReplyBtn(parent_id: String, cell: CommentCell)
  713. }
  714.  
  715. protocol CommentCellDelegate2: class {
  716.     func didTapSubReplyBtn(username:String, parent_id:String, cell: CommentCell)
  717. }
  718.  
  719. class CommentCell:UITableViewCell {
  720.    
  721.     static var shared = CommentCell()
  722.     var imageLoader:DownloadImage?
  723.     var user_image = UIImageView()
  724.     var username = UILabel()
  725.     var stackView = UIStackView()
  726.     var sub_comments:[Comments] = []
  727.     var bottomConstraint:NSLayoutConstraint?
  728.     var svBottomAnchor:NSLayoutConstraint?
  729.     var parent_id:String?
  730.     var user_id:String?
  731.     var offset:Int?
  732.     weak var delegate:UpdateTableView?
  733.     weak var delegate2:CommentCellDelegate2?
  734.     var commentDelegate:CommentCellDelegate?
  735.     let comment_view = CommentView()
  736.     var liked:Bool = false
  737.     var subCommentView:CommentView?
  738.     var profile = SessionManager.shared.profile
  739.     var index:IndexPath?
  740.     var commentsExist:Bool?
  741.     var viewModel: CommentViewModel? {
  742.         didSet {
  743.             if let item = viewModel {
  744.                 print("didSet cell")
  745.                 if let id = item.mainComment?.id, let user_id = profile?.sub {
  746.                   parent_id = id
  747.                   item.loadCommentLikes(id: id)
  748.                   item.getCommentLikesBuIserId(comment_id: id, user_id: user_id)
  749.                   item.commentsExist(comment_id: id, offset: "0", completion: {_ in
  750.                     if item.subComments.isEmpty && item.repliesExist != false {
  751.                         print("item.repliesExist != false")
  752.                         self.repliesBtn.isHidden = false
  753.                         self.repliesBtn.isEnabled = true
  754.                         self.viewMoreBtn.isHidden = true
  755.                     } else {
  756.                         print("item.repliesExist != true")
  757.                     }
  758.                   })
  759.                   }
  760.  
  761.                 imageLoader = DownloadImage()
  762.                 imageLoader?.imageDidSet = { [weak self] image in
  763.                     self?.user_image.image = image
  764.                 }
  765.                 if let picture = item.mainComment?.user_picture {
  766.                 imageLoader?.downloadImage(urlString: picture)
  767.                 }
  768.                 username.text = item.mainComment?.username
  769.                 textView.text = item.mainComment?.text
  770.                 stackView.arrangedSubviews.forEach {
  771.                     stackView.removeArrangedSubview($0)
  772.                     $0.removeFromSuperview()
  773.                 }
  774.                
  775.                 if item.commentsExist == false {
  776.                     viewMoreBtn.isHidden = true
  777.                     viewMoreBtn.isEnabled = false
  778.                 }
  779.                
  780.                 item.commentsExistDidInserts = { [weak self] bool in
  781.                     if bool == false {
  782.                         self?.viewMoreBtn.isHidden = true
  783.                         self?.viewMoreBtn.isEnabled = false
  784.                     }
  785.                 }
  786.                
  787.                 item.subComments.forEach { subComment in
  788.                     subCommentView = CommentView()
  789.                     self.subCommentView?.delegate = self
  790.                     subCommentView?.textView.text = subComment.text
  791.                     print("subComment.text \(subComment.text)")
  792.                     imageLoader?.imageDidSet = { [weak self] image in
  793.                         self?.subCommentView?.user_image.image = image
  794.                     }
  795.                     if let picture = subComment.user_picture {
  796.                     imageLoader?.downloadImage(urlString: picture)
  797.                     }
  798.                     subCommentView?.username.text = subComment.username
  799.                    
  800.                     if let firstIndex = item.subComments.firstIndex(where: { $0.id == subComment.id }) {
  801.                         subCommentView?.likeBtn.tag = firstIndex
  802.                     }
  803.                    
  804.                     if subComment.isliked == true {
  805.                     let image = UIImage(systemName: "heart.fill")
  806.                     subCommentView?.likeBtn.setImage(image, for: .normal)
  807.                     subCommentView?.likeBtn.tintColor = .red
  808.                     }
  809.                     if let numberOfLikes = subComment.numberOfLikes {
  810.                     subCommentView?.numberOfLikes.text = "\(numberOfLikes)"
  811.                     }
  812.  
  813.                     if let commentView = subCommentView {
  814.                     stackView.addArrangedSubview(commentView)
  815.                     }
  816.                  
  817.                 }
  818.  
  819.                 viewMoreBtn.isUserInteractionEnabled = true
  820.                 repliesBtn.isUserInteractionEnabled = true
  821.  
  822.                
  823.        
  824.                 item.likeBtnImageDidSet = { [weak self] in self?.likeBtn.setImage($0, for: .normal) }
  825.                 item.likeBtnTintColorDidSet = { [weak self] in self?.likeBtn.tintColor = $0 }
  826.  
  827.                item.subCommentDidInserts = { [weak self] insertedSubComments in
  828.                
  829.                guard let `self` = self else { return }
  830.                insertedSubComments.forEach { subComment in
  831.                 let subCommentView = CommentView()
  832.                 subCommentView.delegate = self
  833.                 subCommentView.textView.text = subComment.text
  834.                 self.imageLoader?.imageDidSet = { [weak self] image in
  835.                     subCommentView.user_image.image = image
  836.                 }
  837.                 if let picture = subComment.user_picture {
  838.                     self.imageLoader?.downloadImage(urlString: picture)
  839.                 }
  840.                
  841.                 subCommentView.username.text = subComment.username
  842.                 if let firstIndex = item.subComments.firstIndex(where: { $0.id == subComment.id }) {
  843.                     subCommentView.likeBtn.tag = firstIndex
  844.                     subCommentView.numberOfLikes.tag = firstIndex
  845.                 }
  846.  
  847.                     self.stackView.addArrangedSubview(subCommentView)
  848.                    
  849.                    if let comment_id = subComment.id, let user_id = self.profile?.sub {
  850.                        item.getSubCommentLikesByIserId(comment_id: comment_id, user_id: user_id) { [weak subCommentView] bool in
  851.                            if bool == true {
  852.                             let image = UIImage(systemName: "heart.fill")
  853.                             subCommentView?.likeBtn.setImage(image, for: .normal)
  854.                             subCommentView?.likeBtn.tintColor = .red
  855.                             if let index = subCommentView?.likeBtn.tag {
  856.                             item.subComments[index].isliked = true
  857.                          }
  858.                         } else {
  859.                             if let index = subCommentView?.likeBtn.tag {
  860.                              item.subComments[index].isliked = false
  861.                           }
  862.                         }
  863.                      }
  864.                    }
  865.                 if let id = subComment.id {
  866.                     item.loadSubCommentLikes(id: id) {[weak subCommentView] likes in
  867.                         if let index = subCommentView?.likeBtn.tag {
  868.                             item.subComments[index].numberOfLikes = likes.count
  869.                         }
  870.                         subCommentView?.numberOfLikes.text = "\(likes.count)"
  871.                     }
  872.                 }
  873.                    
  874.             }
  875.            
  876.                    
  877.                     UIView.animate(withDuration: 0.5, animations: {
  878.                         self.stackView.isHidden = false
  879.                         self.stackView.alpha = 1
  880.                     })
  881.                     self.viewMoreBtn.setTitle("View More", for: .normal)
  882.                     self.viewMoreBtn.isUserInteractionEnabled = true
  883.                     if item.commentsExist != false {
  884.                     self.viewMoreBtn.isHidden = false
  885.                     self.viewMoreBtn.isEnabled = true
  886.                     }
  887.                     self.repliesBtn.setTitle("View Replies", for: .normal)
  888.                     self.repliesBtn.isUserInteractionEnabled = true
  889.                     self.repliesBtn.isHidden = true
  890.                     self.viewContentLayoutIfNeed()
  891.                 }
  892.                 self.numberOfLikes.text = String(item.commentLikes.count)
  893.                
  894.                 item.commentLikesDidInserts = { [weak self] likes in
  895.                     self?.numberOfLikes.text = String(likes.count)
  896.                 }
  897.            }
  898.         }
  899.     }
  900.    
  901.     var components:URLComponents = {
  902.         var component = URLComponents()
  903.         component.scheme = "http"
  904.         component.host = "localhost"
  905.         component.port = 8000
  906.         return component
  907.     }()
  908.    
  909.     lazy var textView:UITextView = {
  910.         let tv = UITextView()
  911.         tv.isScrollEnabled = false
  912.         tv.isEditable = false
  913.         tv.sizeToFit()
  914.         tv.backgroundColor = UIColor.lightGray
  915.         tv.textContainer.maximumNumberOfLines = 0
  916.         tv.textContainer.lineBreakMode = .byCharWrapping
  917.         tv.font = UIFont(name: "GillSans", size: 18)
  918.         return tv
  919.     }()
  920.    
  921.     lazy var likeBtn:UIButton = {
  922.         let btn = UIButton()
  923.         let symbolConfig = UIImage.SymbolConfiguration(pointSize: 25.0, weight: .medium, scale: .medium)
  924.         let symbol = UIImage(systemName: "heart", withConfiguration: symbolConfig)
  925.         btn.setImage(symbol , for: .normal)
  926.         btn.tintColor = UIColor.darkGray
  927.         btn.addTarget(self, action: #selector(commentLikePressed), for: .touchUpInside)
  928.         return btn
  929.     }()
  930.    
  931.     lazy var numberOfLikes:UILabel = {
  932.         let label = UILabel()
  933.         label.textAlignment = .center
  934.         label.text = "0"
  935.         return label
  936.     }()
  937.    
  938.     lazy var mainReplyBtn:UIButton = {
  939.         let btn = UIButton()
  940.         btn.setTitle("Reply", for: .normal)
  941.         btn.setTitleColor(UIColor.gray, for: .normal)
  942.         btn.titleLabel?.font = .systemFont(ofSize: 12)
  943.         btn.contentHorizontalAlignment = .left
  944.         btn.addTarget(self, action: #selector(mainCommentReplyPressed), for: .touchUpInside)
  945.         return btn
  946.     }()
  947.    
  948.     lazy var repliesBtn:UIButton = {
  949.         let btn = UIButton()
  950.         btn.setTitle("View Replies", for: .normal)
  951.         btn.setTitleColor(UIColor.gray, for: .normal)
  952.         btn.titleLabel?.font = .systemFont(ofSize: 12)
  953.         btn.contentHorizontalAlignment = .left
  954.         btn.isHidden = true
  955.         btn.isEnabled = false
  956.         btn.addTarget(self, action: #selector(repliesBtnPressed), for: .touchUpInside)
  957.         return btn
  958.     }()
  959.    
  960.     lazy var viewMoreBtn:UIButton = {
  961.         let btn = UIButton()
  962.         btn.setTitle("View More", for: .normal)
  963.         btn.setTitleColor(UIColor.gray, for: .normal)
  964.         btn.titleLabel?.font = .systemFont(ofSize: 12)
  965.         btn.contentHorizontalAlignment = .left
  966.         btn.isHidden = true
  967.         btn.isEnabled = false
  968.         btn.addTarget(self, action: #selector(viewMorePressed), for: .touchUpInside)
  969.         return btn
  970.     }()
  971.    
  972.    
  973.     override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
  974.         super.init(style: style, reuseIdentifier: reuseIdentifier)
  975.         addSubview(user_image)
  976.         setImageConstraints()
  977.         setUsername()
  978.         addSubview(username)
  979.         setUsernameConstraints()
  980.         addSubview(textView)
  981.         addSubview(mainReplyBtn)
  982.         addSubview(repliesBtn)
  983.         addSubview(viewMoreBtn)
  984.         addSubview(likeBtn)
  985.         addSubview(numberOfLikes)
  986.         configureStackView()
  987.         textViewContstraints()
  988.         commentLikeBtnConstraints()
  989.         commentLikesConstraints()
  990.         mainCommentReplyBtnConstraints()
  991.         print("Text view bottomAnchor init \(textView.bottomAnchor.description)")
  992.         setStackViewContstraints()
  993.         repliesBtnConstraints()
  994.         viewMoreBtnConstraints()
  995.        
  996.     }
  997.    
  998.     required init?(coder: NSCoder) {
  999.         fatalError("init(coder:) has not been implemented")
  1000.     }
  1001.    
  1002.     func addedSubComment() {
  1003.           if let id = self.parent_id, let user_id = profile?.sub {
  1004.             self.viewModel?.loadSubCommentsAfterReply(comment_id: id, user_id: user_id)
  1005.         }
  1006.     }
  1007.    
  1008.     @objc func commentLikePressed() {
  1009.         guard let viewModel = viewModel else { return }
  1010.         if viewModel.isLiked {
  1011.             if let comment_id = parent_id, let user_id = profile?.sub {
  1012.             viewModel.unlikeComment(comment_id: comment_id, user_id: user_id)
  1013.             }
  1014.         } else {
  1015.             if let user_id = profile?.sub, let comment_id = parent_id {
  1016.             viewModel.likeComment(user_id: user_id, comment_id: comment_id)
  1017.             }
  1018.         }
  1019.     }
  1020.    
  1021.    
  1022.     @objc func mainCommentReplyPressed() {
  1023.         if let parent_id = parent_id {
  1024.             commentDelegate?.didTapReplyBtn(parent_id: parent_id, cell: self)
  1025.         }
  1026.     }
  1027.    
  1028.     @objc func repliesBtnPressed() {
  1029.         repliesBtn.setTitle("Loading...", for: .normal)
  1030.         repliesBtn.isUserInteractionEnabled = false
  1031.         if let id = self.parent_id {
  1032.         viewModel?.updateParentId(newString: id)
  1033.             viewModel?.reply(id:id, completion: {
  1034.                 self.repliesBtn.isHidden = true
  1035.                 if self.viewModel?.commentsExist != false {
  1036.                      self.viewMoreBtn.isHidden = false
  1037.                      self.viewMoreBtn.isEnabled = true
  1038.                  }
  1039.             })
  1040.         }
  1041.        
  1042.     }
  1043.    
  1044.    
  1045.     @objc func viewMorePressed() {
  1046.         viewMoreBtn.setTitle("Loading...", for: .normal)
  1047.         viewMoreBtn.isUserInteractionEnabled = false
  1048.         if let id = self.parent_id {
  1049.         viewModel?.updateParentId(newString: id)
  1050.             viewModel?.viewMore(id: id, completion: {
  1051.                 if self.viewModel?.commentsExist != false {
  1052.                     self.viewMoreBtn.isHidden = false
  1053.                     self.viewMoreBtn.isEnabled = true
  1054.                 }
  1055.             })
  1056.         }
  1057.     }
  1058.    
  1059.    
  1060.     func configureStackView() {
  1061.         addSubview(stackView)
  1062.         stackView.axis = .vertical
  1063.         stackView.distribution = .fillProportionally
  1064.         stackView.spacing = 5
  1065.     }
  1066.    
  1067.     func commentLikesConstraints() {
  1068.         numberOfLikes.translatesAutoresizingMaskIntoConstraints = false
  1069.         numberOfLikes.widthAnchor.constraint(equalToConstant: 60).isActive = true
  1070.         numberOfLikes.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1071.         numberOfLikes.centerXAnchor.constraint(equalTo: likeBtn.centerXAnchor).isActive = true
  1072.         numberOfLikes.topAnchor.constraint(equalTo: likeBtn.bottomAnchor, constant: -5).isActive = true
  1073.     }
  1074.    
  1075.     func commentLikeBtnConstraints() {
  1076.         likeBtn.translatesAutoresizingMaskIntoConstraints = false
  1077.         likeBtn.widthAnchor.constraint(equalToConstant: 60).isActive = true
  1078.         likeBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1079.         likeBtn.leadingAnchor.constraint(equalTo: textView.trailingAnchor, constant: 3).isActive = true
  1080.         likeBtn.topAnchor.constraint(equalTo: textView.topAnchor, constant: -5).isActive = true
  1081.     }
  1082.    
  1083.    
  1084.  
  1085.     func mainCommentReplyBtnConstraints() {
  1086.         mainReplyBtn.translatesAutoresizingMaskIntoConstraints = false
  1087.         mainReplyBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
  1088.         mainReplyBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1089.         mainReplyBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
  1090.         mainReplyBtn.topAnchor.constraint(equalTo: textView.bottomAnchor, constant: 1).isActive = true
  1091.        
  1092.     }
  1093.    
  1094.  
  1095.    
  1096.     func setStackViewContstraints() {
  1097.         stackView.translatesAutoresizingMaskIntoConstraints = false
  1098.         stackView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -30).isActive = true
  1099.         stackView.topAnchor.constraint(equalTo: mainReplyBtn.bottomAnchor, constant: 42).isActive = true
  1100.        
  1101.         stackView.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
  1102.         stackView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
  1103.        
  1104.     }
  1105.    
  1106.    
  1107.    
  1108.     func setImageConstraints() {
  1109.         user_image.translatesAutoresizingMaskIntoConstraints = false
  1110.         user_image.topAnchor.constraint(equalTo: topAnchor, constant: 5).isActive = true
  1111.         user_image.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 8).isActive = true
  1112.         user_image.heightAnchor.constraint(equalToConstant: 40).isActive = true
  1113.         user_image.widthAnchor.constraint(equalToConstant: 40).isActive = true
  1114.        
  1115.     }
  1116.    
  1117.    
  1118.     func setUsername() {
  1119.         username.textColor = UIColor.gray
  1120.         username.font = UIFont.systemFont(ofSize: 14)
  1121.     }
  1122.    
  1123.     func setUsernameConstraints() {
  1124.         username.translatesAutoresizingMaskIntoConstraints = false
  1125.         username.topAnchor.constraint(equalTo: user_image.topAnchor, constant: 5).isActive = true
  1126.         username.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
  1127.         username.heightAnchor.constraint(equalToConstant: 10).isActive = true
  1128.         username.widthAnchor.constraint(equalTo: widthAnchor).isActive = true
  1129.     }
  1130.    
  1131.     func textViewContstraints() {
  1132.         textView.translatesAutoresizingMaskIntoConstraints = false
  1133.         textView.topAnchor.constraint(equalTo: username.bottomAnchor, constant: 5).isActive = true
  1134.         textView.leadingAnchor.constraint(equalTo: user_image.trailingAnchor, constant: 8).isActive = true
  1135.         textView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -60).isActive = true
  1136.        
  1137.     }
  1138.    
  1139.     func repliesBtnConstraints() {
  1140.         repliesBtn.translatesAutoresizingMaskIntoConstraints = false
  1141.         bottomConstraint =
  1142.         repliesBtn.bottomAnchor.constraint(equalTo: stackView.topAnchor)
  1143.         bottomConstraint?.isActive = true
  1144.         repliesBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
  1145.         repliesBtn.heightAnchor.constraint(equalToConstant: 30).isActive = true
  1146.         repliesBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor).isActive = true
  1147.         repliesBtn.topAnchor.constraint(equalTo: mainReplyBtn.bottomAnchor).isActive = true
  1148.        
  1149.     }
  1150.    
  1151.    
  1152.    
  1153.     func viewMoreBtnConstraints() {
  1154.         viewMoreBtn.translatesAutoresizingMaskIntoConstraints = false
  1155.         viewMoreBtn.widthAnchor.constraint(equalToConstant: 100).isActive = true
  1156.         viewMoreBtn.heightAnchor.constraint(equalToConstant: 20).isActive = true
  1157.         viewMoreBtn.leadingAnchor.constraint(equalTo: textView.leadingAnchor, constant: 5).isActive = true
  1158.         viewMoreBtn.topAnchor.constraint(equalTo: stackView.bottomAnchor, constant: 9).isActive = true
  1159.        
  1160.     }
  1161.    
  1162.  
  1163.    
  1164. }
  1165.  
  1166. extension CommentCell: CommentViewDelegate {
  1167.    
  1168.  
  1169.     func replyToSubComment(sender: UIButton) {
  1170.         let subCommentView = sender.superview as! CommentView
  1171.         if let username = subCommentView.username.text, let parent_id = parent_id {
  1172.             delegate2?.didTapSubReplyBtn(username: username, parent_id: parent_id, cell: self)
  1173.         }
  1174.     }
  1175.    
  1176.      @objc func subCommentLikePressed(sender:UIButton) {
  1177.            var comment_id:String?
  1178.            
  1179.            comment_id = viewModel?.subComments[sender.tag].id
  1180.            guard let viewModel = viewModel else { return }
  1181.            if viewModel.subComments[sender.tag].isliked == true {
  1182.            
  1183.               if let user_id = profile?.sub, let comment_id = comment_id {
  1184.                 viewModel.unlikeSubComment(comment_id: comment_id, user_id: user_id, completion: {
  1185.                     DispatchQueue.main.async {
  1186.                     if let id = viewModel.subComments[sender.tag].id {
  1187.                               viewModel.loadSubCommentLikes(id: "\(id)", completion: { likes in
  1188.                                   let subCommentView = sender.superview as! CommentView
  1189.                                   subCommentView.numberOfLikes.text = "\(likes.count)"
  1190.                                   viewModel.subComments[sender.tag].numberOfLikes = likes.count
  1191.                                  
  1192.                               })
  1193.                              
  1194.                               }
  1195.                     }
  1196.                 })
  1197.                    
  1198.                }
  1199.             let image = UIImage(systemName: "heart")
  1200.             sender.setImage(image, for: .normal)
  1201.             sender.tintColor = .darkGray
  1202.  
  1203.             viewModel.subComments[sender.tag].isliked = false
  1204.          } else if viewModel.subComments[sender.tag].isliked == false {
  1205.            
  1206.                if let user_id = profile?.sub, let comment_id = comment_id {
  1207.                 viewModel.likeSubComment(user_id: user_id, comment_id: comment_id, completion: {
  1208.                     DispatchQueue.main.async {
  1209.                     if let id = viewModel.subComments[sender.tag].id {
  1210.                     viewModel.loadSubCommentLikes(id: "\(id)", completion: { likes in
  1211.                         let subCommentView = sender.superview as! CommentView
  1212.                         subCommentView.numberOfLikes.text = "\(likes.count)"
  1213.                         viewModel.subComments[sender.tag].numberOfLikes = likes.count
  1214.                        
  1215.                        
  1216.                     })
  1217.                     }
  1218.                   }
  1219.                 })
  1220.                 let image = UIImage(systemName: "heart.fill")
  1221.                 sender.setImage(image, for: .normal)
  1222.                 sender.tintColor = .red
  1223.                
  1224.                }
  1225.                viewModel.subComments[sender.tag].isliked = true
  1226.           }
  1227.        }
  1228.    
  1229. }
  1230.  
  1231. import UIKit
  1232. import Foundation
  1233.  
  1234. class CommentViewModel {
  1235.     var offset: Int = 0
  1236.     static var offsetForCell: Int = 0
  1237.     var buttonTag:[Int] = []
  1238.     static var parent_id:String?
  1239.     var mainComment: Comments?
  1240.     var mainCommentImage: UIImage?
  1241.     var commentLikes: [CommentLikes] = []
  1242.     var commentLikesDidInserts: (([CommentLikes]) -> ())?
  1243.     var subComments: [Comments] = []
  1244.     var subCommentDidInserts: (([Comments]) -> ())?
  1245.     var imageDownloader: DownloadImage?
  1246.     var symbolConfig = UIImage.SymbolConfiguration(pointSize: 25.0, weight: .medium, scale: .medium)
  1247.     var likeBtnImage: UIImage? = UIImage(systemName: "heart")  { didSet { likeBtnImageDidSet?(likeBtnImage) } }
  1248.     var likeBtnImageDidSet: ((UIImage?)->())?
  1249.     var likeBtnTintColor: UIColor? = UIColor.darkGray { didSet { likeBtnTintColorDidSet?(likeBtnTintColor) } }
  1250.     var likeBtnTintColorDidSet: ((UIColor?)->())?
  1251.     var isLiked: Bool = false
  1252.     var isLikedLoaded: Bool = false
  1253.     var commentsExist:Bool?
  1254.     var commentsExistDidInserts: ((Bool) -> ())?
  1255.     var repliesExist:Bool?
  1256.     var repliesExistDidInserts: ((Bool) -> ())?
  1257.  
  1258.  
  1259.    
  1260.     func viewMore(id: String,  completion: @escaping () -> ()) {
  1261.         offset += 3
  1262.         loadSubComments()
  1263.         let offset2 = offset + 3
  1264.         commentsExist(comment_id: id, offset:"\(offset2)", completion: { comment in
  1265.            if comment.count <= 0 {
  1266.                
  1267.                 self.commentsExist = false
  1268.                 self.commentsExistDidInserts?(false)
  1269.                 completion()
  1270.            }
  1271.         })
  1272.     }
  1273.    
  1274.     func reply(id: String, completion: @escaping () -> ()) {
  1275.         offset = 0
  1276.         loadSubComments()
  1277.         let offset2 = offset + 3
  1278.         commentsExist(comment_id: id, offset:"\(offset2)", completion: { comment in
  1279.            if comment.count <= 0 {
  1280.              
  1281.                 self.commentsExist = false
  1282.                 self.commentsExistDidInserts?(false)
  1283.                 completion()
  1284.            }
  1285.         })
  1286.     }
  1287.    
  1288.    
  1289.     func loadSubComments() {
  1290.         print("loadSubComments")
  1291.         let getSubComments = GETSubComments(id: CommentViewModel.parent_id, path: "subComments", offset: "\(offset)")
  1292.             getSubComments.getAllById {
  1293.                    self.subComments += $0
  1294.                    self.subCommentDidInserts?($0)
  1295.              
  1296.         }
  1297.     }
  1298.    
  1299.     func commentsExist(comment_id: String, offset: String, completion: @escaping ([Comments]) -> ()) {
  1300.         let getSubComments = GETSubComments(id: comment_id, path: "subComments", offset: "\(offset)")
  1301.             getSubComments.getAllById {
  1302.                    if $0.count <= 0 {
  1303.                     print("commentsExist now \($0)")
  1304.                     self.repliesExist = false
  1305.                     self.repliesExistDidInserts?(false)
  1306.                     } else {
  1307.                     self.repliesExist = true
  1308.                     self.repliesExistDidInserts?(true)
  1309.                 }
  1310.                 completion($0)
  1311.         }
  1312.     }
  1313.    
  1314.     func loadSubCommentsAfterReply(comment_id:String?, user_id:String?) {
  1315.        
  1316.         if let id = comment_id {
  1317.         let getSubComments = GETSubCommentAfterReply(id: id, user_id: user_id)
  1318.  
  1319.             getSubComments.getSubComment {
  1320.                    self.subComments += $0
  1321.                    self.subCommentDidInserts?($0)
  1322.                    let offset2 = self.offset + 3
  1323.                    if let comment_id = comment_id {
  1324.                     self.commentsExist(comment_id: comment_id, offset:"\(offset2)", completion: { comment in
  1325.                    if comment.count <= 0 {
  1326.                         self.commentsExist = false
  1327.                         self.commentsExistDidInserts?(false)
  1328.                    }
  1329.                   })
  1330.                 }
  1331.                  
  1332.         }
  1333.       }
  1334.     }
  1335.    
  1336.     func loadCommentLikes(id:String) {
  1337.         print("loadCommentLikes")
  1338.         let getCommentLikes = GETCommentLikes(id: id)
  1339.         getCommentLikes.getAllById {
  1340.             self.commentLikes = $0
  1341.             self.commentLikesDidInserts?($0)
  1342.         }
  1343.     }
  1344.    
  1345.     func getCommentLikesBuIserId(comment_id:String, user_id:String) {
  1346.            guard isLikedLoaded == false else { return }
  1347.            
  1348.           let getLikeByUser = GETCommentLikesByUserID(comment_id: comment_id, user_id: user_id)
  1349.            
  1350.            getLikeByUser.getAllById {
  1351.                if $0.count > 0 {
  1352.                self.likeBtnImage = UIImage(systemName: "heart.fill")
  1353.                self.likeBtnTintColor = .red
  1354.            
  1355.                self.isLiked = true
  1356.                self.isLikedLoaded = true
  1357.            }
  1358.        }
  1359.     }
  1360.    
  1361.     func likeComment(user_id: String, comment_id: String) {
  1362.          let commentLike = CommentLike(user_id: user_id, comment_id: comment_id)
  1363.                
  1364.                
  1365.                let postRequest = CommentLikePostRequest(endpoint: "addCommentLike")
  1366.                postRequest.save(commentLike) { (result) in
  1367.                    switch result {
  1368.                    case .success(let comment):
  1369.                        print("the following comment like has been sent: \(commentLike)")
  1370.                        self.loadCommentLikes(id: comment_id)
  1371.                    case .failure(let error):
  1372.                        print("An error occurred: \(error)")
  1373.                    }
  1374.                }
  1375.             self.likeBtnImage = UIImage(systemName: "heart.fill")
  1376.             self.likeBtnTintColor = .red
  1377.             self.isLiked = true
  1378.     }
  1379.    
  1380.     func unlikeComment(comment_id: String, user_id: String) {
  1381.        let deleteRequest = DLTCommentLike(comment_id: comment_id, user_id: user_id)
  1382.        
  1383.         deleteRequest.delete {(err) in
  1384.             if let err = err {
  1385.                 print("Failed to delete", err)
  1386.                 return
  1387.             }
  1388.             self.loadCommentLikes(id: comment_id)
  1389.             print("Successfully deleted comment like from server")
  1390.             }
  1391.             self.likeBtnImage = UIImage(systemName: "heart")
  1392.             self.likeBtnTintColor = .darkGray
  1393.             self.isLiked = false
  1394.     }
  1395.    
  1396.    
  1397.     func getSubCommentLikesByIserId(comment_id:String, user_id:String, completion: @escaping (Bool) -> ()) {
  1398.           print("it worked")
  1399.           let getLikeByUser = GETCommentLikesByUserID(comment_id: comment_id, user_id: user_id)
  1400.            
  1401.            getLikeByUser.getAllById {
  1402.                if $0.count > 0 {
  1403.                completion(true)
  1404.             } else {
  1405.                completion(false)
  1406.           }
  1407.        }
  1408.     }
  1409.    
  1410.     func likeSubComment(user_id: String, comment_id: String, completion: @escaping () -> ()) {
  1411.         let commentLike = CommentLike(user_id: user_id, comment_id: comment_id)
  1412.        
  1413.         let postRequest = CommentLikePostRequest(endpoint: "addCommentLike")
  1414.         postRequest.save(commentLike) { (result) in
  1415.             switch result {
  1416.             case .success(let comment):
  1417.                 print("the following sub comment like has been sent: \(commentLike)")
  1418.                 completion()
  1419.             case .failure(let error):
  1420.                 print("An error occurred: \(error)")
  1421.             }
  1422.         }
  1423.     }
  1424.    
  1425.     func unlikeSubComment(comment_id: String, user_id: String, completion: @escaping () -> ()) {
  1426.        let deleteRequest = DLTCommentLike(comment_id: comment_id, user_id: user_id)
  1427.        
  1428.         deleteRequest.delete {(err) in
  1429.             if let err = err {
  1430.                 print("Failed to delete", err)
  1431.                 return
  1432.             }
  1433.             completion()
  1434.             print("Successfully deleted sub comment like from server")
  1435.             }
  1436.     }
  1437.    
  1438.     func loadSubCommentLikes(id:String, completion: @escaping ([CommentLikes]) -> ()) {
  1439.         print("loadSubCommentLikes")
  1440.         let getCommentLikes = GETCommentLikes(id: id)
  1441.         getCommentLikes.getAllById {
  1442.              completion($0)
  1443.         }
  1444.     }
  1445.    
  1446.    
  1447.    
  1448.     func updateParentId(newString:String) {
  1449.         CommentViewModel.self.parent_id = newString
  1450.     }
  1451.    
  1452.     func updateOffsetForCell(newInt:Int) {
  1453.         CommentViewModel.self.offsetForCell = newInt
  1454.     }
  1455.    
  1456.    
  1457. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement