<commit_before>//
// Copyright (c) 2016 eBay Software Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

import UIKit
import AsyncDisplayKit

//MARK: MessageGroup
/**
 Holds a group of messages. Extends GeneralMessengerCell.
 */
open class MessageGroup: GeneralMessengerCell {
    
    /** Used for current state of new/old messages*/
    public enum MessageGroupState {
        case added
        case removed
        case replaced
        case none
    }
    
    // MARK: Public Variables
    open weak var delegate: MessageCellProtocol?
    /** Holds a table of GeneralMessengerCells*/
    open fileprivate(set) var messageTable = ASTableNode(style: .plain)
    /** Set to true when the after the component has laid out for the first time*/
    open fileprivate(set) var hasLaidOut = false
    /** Data set for messages in the group */
    open fileprivate(set) var messages = [GeneralMessengerCell]()
    /** Delay before add/remove animation begins*/
    open var animationDelay: TimeInterval = 0
    /** Avatar new message animation speed */
    open var avatarAnimationSpeed: TimeInterval = 0.15
    
    /**
     Spacing around the avatar
     */
    open var avatarInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10) {
        didSet {
            self.setNeedsLayout()
        }
    }
    
    /**
     Message offset spacing from the edge (avatar or messenger bounds)
     */
    open var messageOffset: CGFloat = 10 {
        didSet {
            self.setNeedsLayout()
        }
    }
    
    /** ASDisplayNode as the avatar of the cell*/
    open var avatarNode: ASDisplayNode?
        {
        willSet{
            if let avatarNode = newValue {
                if let oldAvatar = self.avatarNode {
                    self.insertSubnode(avatarNode, aboveSubnode: oldAvatar)
                    self.insertSubnode(self.avatarButtonNode, aboveSubnode: avatarNode)
                    oldAvatar.removeFromSupernode()
                    self.avatarButtonNode.removeFromSupernode()
                } else {
                    self.addSubnode(avatarNode)
                    self.addSubnode(self.avatarButtonNode)
                }
            }
        }
        didSet {
            self.setNeedsLayout()
        }
    }
    
    /** Bool if the cell is an incoming or out going message cell*/
    open override var isIncomingMessage:Bool {
        didSet {
            for message in messages {
                if let message = message as? MessageNode {
                    message.isIncomingMessage = isIncomingMessage
                }
            }
        }
    }
    
    //MARK: Private variables
    /** Layout completion block for adding/removing messages*/
    fileprivate var layoutCompletionBlock: (()->Void)?
    /** Current state of new/old messages*/
    fileprivate var state: MessageGroupState?
    /** Default animation delay time for ASTableView*/
    fileprivate let tableviewAnimationDelay:TimeInterval = 0.3
    /** Button node to handle avatar click*/
    fileprivate var avatarButtonNode: ASControlNode = ASControlNode()
    
    //MARK: Initializers
    
    public override init() {
        super.init()
        self.setupTable()
        self.setupAvatarButton()
    }
    
    /** Initializes the ASTableNode for a group of messages*/
    fileprivate func setupTable() {
        self.messageTable.delegate = self
        self.messageTable.dataSource = self
        
        self.messageTable.view.separatorStyle = .none
        self.messageTable.view.isScrollEnabled = false
        self.messageTable.view.showsVerticalScrollIndicator = false
        
        self.addSubnode(self.messageTable)
    }
    
    /** Creates a listener for the avatar button */
    fileprivate func setupAvatarButton() {
        self.avatarButtonNode.addTarget(self, action:  #selector(MessageGroup.avatarClicked), forControlEvents: .touchUpInside)
        self.avatarButtonNode.isExclusiveTouch = true
    }
    
    // MARK: Override AsycDisaplyKit Methods
    
    /**
     Overriding layoutSpecThatFits to specifiy relatiohsips between elements in the cell
     */
    override open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
        var tableWidth:CGFloat = 0
        
        let justifyLocation = isIncomingMessage ? ASStackLayoutJustifyContent.start : ASStackLayoutJustifyContent.end
        
        //make a space for the avatar if needed
        if let avatarNode = self.avatarNode {
            let layoutSize = avatarNode.layoutThatFits(ASSizeRangeMake(CGSize.zero, constrainedSize.max))
            tableWidth = constrainedSize.max.width - layoutSize.size.width - self.avatarInsets.left - self.avatarInsets.right - self.cellPadding.left - self.cellPadding.right - messageOffset
        } else {
            tableWidth = constrainedSize.max.width - self.cellPadding.left - self.cellPadding.right - self.messageOffset
        }
        
        var elementHeight:CGFloat = 0
        
        //get the size of every message in the group to calculate height
        for message in messages {
            let newSize = ASSizeRange(min: constrainedSize.min, max: CGSize(width: tableWidth, height: constrainedSize.max.height))
            let size = message.layoutThatFits(newSize).size
            print(size)
            elementHeight += size.height
        }
        self.messageTable.style.preferredSize = CGSize(width: tableWidth, height: elementHeight)
        
        var retLayout:ASLayoutSpec = ASAbsoluteLayoutSpec(sizing: .sizeToFit, children: [self.messageTable])
        
        var stackLayout: ASStackLayoutSpec?
        var insetLayout: ASInsetLayoutSpec?
        let spacer = ASLayoutSpec()
        
        //add the avatar to the layout
        if let avatarNode = self.avatarNode {
            let avatarSizeLayout = ASAbsoluteLayoutSpec()
            avatarSizeLayout.sizing = .sizeToFit
            avatarSizeLayout.children = [avatarNode]
            
            //create avatar button
            self.avatarButtonNode.style.preferredSize = avatarNode.layoutThatFits(ASSizeRange(min: CGSize.zero, max: constrainedSize.max)).size
            let avatarButtonSizeLayout = ASAbsoluteLayoutSpec()<commit_msg>Fix message group layout bug<commit_after>//
// Copyright (c) 2016 eBay Software Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

import UIKit
import AsyncDisplayKit

//MARK: MessageGroup
/**
 Holds a group of messages. Extends GeneralMessengerCell.
 */
open class MessageGroup: GeneralMessengerCell {
    
    /** Used for current state of new/old messages*/
    public enum MessageGroupState {
        case added
        case removed
        case replaced
        case none
    }
    
    // MARK: Public Variables
    open weak var delegate: MessageCellProtocol?
    /** Holds a table of GeneralMessengerCells*/
    open fileprivate(set) var messageTable = ASTableNode(style: .plain)
    /** Set to true when the after the component has laid out for the first time*/
    open fileprivate(set) var hasLaidOut = false
    /** Data set for messages in the group */
    open fileprivate(set) var messages = [GeneralMessengerCell]()
    /** Delay before add/remove animation begins*/
    open var animationDelay: TimeInterval = 0
    /** Avatar new message animation speed */
    open var avatarAnimationSpeed: TimeInterval = 0.15
    
    /**
     Spacing around the avatar
     */
    open var avatarInsets: UIEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 10) {
        didSet {
            self.setNeedsLayout()
        }
    }
    
    /**
     Message offset spacing from the edge (avatar or messenger bounds)
     */
    open var messageOffset: CGFloat = 10 {
        didSet {
            self.setNeedsLayout()
        }
    }
    
    /** ASDisplayNode as the avatar of the cell*/
    open var avatarNode: ASDisplayNode?
        {
        willSet{
            if let avatarNode = newValue {
                if let oldAvatar = self.avatarNode {
                    self.insertSubnode(avatarNode, aboveSubnode: oldAvatar)
                    self.insertSubnode(self.avatarButtonNode, aboveSubnode: avatarNode)
                    oldAvatar.removeFromSupernode()
                    self.avatarButtonNode.removeFromSupernode()
                } else {
                    self.addSubnode(avatarNode)
                    self.addSubnode(self.avatarButtonNode)
                }
            }
        }
        didSet {
            self.setNeedsLayout()
        }
    }
    
    /** Bool if the cell is an incoming or out going message cell*/
    open override var isIncomingMessage:Bool {
        didSet {
            for message in messages {
                if let message = message as? MessageNode {
                    message.isIncomingMessage = isIncomingMessage
                }
            }
        }
    }
    
    //MARK: Private variables
    /** Layout completion block for adding/removing messages*/
    fileprivate var layoutCompletionBlock: (()->Void)?
    /** Current state of new/old messages*/
    fileprivate var state: MessageGroupState?
    /** Default animation delay time for ASTableView*/
    fileprivate let tableviewAnimationDelay:TimeInterval = 0.3
    /** Button node to handle avatar click*/
    fileprivate var avatarButtonNode: ASControlNode = ASControlNode()
    
    //MARK: Initializers
    
    public override init() {
        super.init()
        self.setupTable()
        self.setupAvatarButton()
    }
    
    /** Initializes the ASTableNode for a group of messages*/
    fileprivate func setupTable() {
        self.messageTable.delegate = self
        self.messageTable.dataSource = self
        
        self.messageTable.view.separatorStyle = .none
        self.messageTable.view.isScrollEnabled = false
        self.messageTable.view.showsVerticalScrollIndicator = false
        
        self.addSubnode(self.messageTable)
    }
    
    /** Creates a listener for the avatar button */
    fileprivate func setupAvatarButton() {
        self.avatarButtonNode.addTarget(self, action:  #selector(MessageGroup.avatarClicked), forControlEvents: .touchUpInside)
        self.avatarButtonNode.isExclusiveTouch = true
    }
    
    // MARK: Override AsycDisaplyKit Methods
    
    /**
     Overriding layoutSpecThatFits to specifiy relatiohsips between elements in the cell
     */
    override open func layoutSpecThatFits(_ constrainedSize: ASSizeRange) -> ASLayoutSpec {
        var tableWidth:CGFloat = 0
        
        let justifyLocation = isIncomingMessage ? ASStackLayoutJustifyContent.start : ASStackLayoutJustifyContent.end
        
        //make a space for the avatar if needed
        if let avatarNode = self.avatarNode {
            let layoutSize = avatarNode.layoutThatFits(ASSizeRangeMake(CGSize.zero, constrainedSize.max))
            tableWidth = constrainedSize.max.width - layoutSize.size.width - self.avatarInsets.left - self.avatarInsets.right - self.cellPadding.left - self.cellPadding.right - messageOffset
        } else {
            tableWidth = constrainedSize.max.width - self.cellPadding.left - self.cellPadding.right - self.messageOffset
        }
        
        var elementHeight:CGFloat = 0
        
        //get the size of every message in the group to calculate height
        for message in messages {
            let newSize = ASSizeRange(min: CGSize(width: tableWidth, height: 0), max: CGSize(width: tableWidth, height: constrainedSize.max.height))
            
            let size = message.layoutThatFits(newSize).size
            print(size)
            elementHeight += size.height
        }
        self.messageTable.style.preferredSize = CGSize(width: tableWidth, height: elementHeight)
        
        var retLayout:ASLayoutSpec = ASAbsoluteLayoutSpec(sizing: .sizeToFit, children: [self.messageTable])
        
        var stackLayout: ASStackLayoutSpec?
        var insetLayout: ASInsetLayoutSpec?
        let spacer = ASLayoutSpec()
        
        //add the avatar to the layout
        if let avatarNode = self.avatarNode {
            let avatarSizeLayout = ASAbsoluteLayoutSpec()
            avatarSizeLayout.sizing = .sizeToFit
            avatarSizeLayout.children = [avatarNode]
            
            //create avatar button
            self.avatarButtonNode.style.preferredSize = avatarNode.layoutThatFits(ASSizeRange(min: CGSize.zero, max: constrainedSize.max)).size
            let avatarButtonSizeLayout = ASAbsoluteLayoutSpec()
{'fraction_non_alphanumeric': 0.0705034974721241, 'fraction_numerical': 0.0027010180760440473, 'mean_word_length': 2.4234234234234235, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3521017', 'n_tokens_mistral': 3811, 'n_tokens_neox': 3633, 'n_words': 1204}