
//
// © 2017-2020 Qualcomm Technologies, Inc. and/or its subsidiaries. All rights reserved.
//

import UIKit

enum MasterViewControllerTableViewCellActionType {
    case none
    case play
    case pause
    case toggleOn
    case toggleOff
}

protocol MasterViewControllerTableViewCellDelegate: class {
    func cell(_ cell: MasterViewControllerTableViewCell,
              didTapActionForItem item: MasterViewControllerDisplayable)

    func cell(_ cell: MasterViewControllerTableViewCell,
              didTapOptionsButtonForItem item: MasterViewControllerDisplayable)
}



class MasterViewControllerTableViewCell: UITableViewCell {
    @IBOutlet private weak var titleLabel: UILabel!
	@IBOutlet private weak var typeImageView: UIImageView!
    @IBOutlet private weak var firstAdditionalTextLabel: UILabel!
    @IBOutlet private weak var secondAdditionalTextLabel: UILabel!
    @IBOutlet private weak var optionsButton: UIButton!
    @IBOutlet private weak var actionButton: UIButton!
    @IBOutlet private weak var btDevicesPairedImageView: UIImageView!
    @IBOutlet private weak var zbDevicesPairedImageView: UIImageView!
    @IBOutlet private weak var containerView: UIView!
    @IBOutlet private weak var indentImageStackView: UIStackView!
    @IBOutlet private weak var indentImageStackViewWidthLayoutConstraint: NSLayoutConstraint!
    @IBOutlet private weak var bottomIndentImage: TreeIndentView!

    @IBOutlet private weak var bottomView: UIView!
    @IBOutlet private weak var bottomViewHeightLayoutConstraint: NSLayoutConstraint!

    weak var delegate: MasterViewControllerTableViewCellDelegate?
    var actionType = MasterViewControllerTableViewCellActionType.none {
        didSet {
            switch actionType {
            case .none:
                actionButton.isHidden = true
            case .play:
                actionButton.isHidden = false
                if let unwrappedItem = item {
                    actionButton.makeAccessible(unwrappedItem.name, localizableSuffix: Accessibility.HomeScreen.CellSuffix.playButton)
                }
                actionButton.setImage(UIImage(named: "btn-play-pressed"), for: .normal)
                actionButton.setImage(UIImage(named: "btn-play-pressed"), for: .selected)
                actionButton.setImage(UIImage(named: "btn-play-pressed"), for: .highlighted)
            case .pause:
                actionButton.isHidden = false
                if let unwrappedItem = item {
                    actionButton.makeAccessible(unwrappedItem.name, localizableSuffix: Accessibility.HomeScreen.CellSuffix.pauseButton)
                }
                actionButton.setImage(UIImage(named: "btn-pause-pressed"), for: .normal)
                actionButton.setImage(UIImage(named: "btn-pause-pressed"), for: .selected)
                actionButton.setImage(UIImage(named: "btn-pause-pressed"), for: .highlighted)
            case .toggleOn:
                actionButton.isHidden = true
            case .toggleOff:
                actionButton.isHidden = true
            }
        }
    }
    
    var item: MasterViewControllerDisplayable? {
        didSet {
            if let unwrappedItem = item {
                titleLabel.text = unwrappedItem.name.uppercased()
                if unwrappedItem.available {
                    titleLabel.textColor = UIColor.darkText
                } else {
                    titleLabel.textColor = UIColor.lightGray
                }
                
                makeAccessible(unwrappedItem.name, localizableSuffix: Accessibility.HomeScreen.CellSuffix.row)
                optionsButton.makeAccessible(unwrappedItem.name, localizableSuffix: Accessibility.HomeScreen.CellSuffix.optionsButton)
                
                expanded = unwrappedItem.stateDescription.count > 0
                firstAdditionalTextLabel.text = unwrappedItem.stateDescription.first ?? ""
                if unwrappedItem.stateDescription.count > 1 {
                    secondAdditionalTextLabel.isHidden = false
                	secondAdditionalTextLabel.text = unwrappedItem.stateDescription[1]
                } else {
                    secondAdditionalTextLabel.isHidden = true
					secondAdditionalTextLabel.text = ""
                }
                optionsButton.isHidden = !(unwrappedItem.encapsulatedType == .speaker ||
                    unwrappedItem.encapsulatedType == .speakerGroup ||
                    unwrappedItem.encapsulatedType == .speakerConvenienceGroup)

                drawTree(unwrappedItem)
                setIcon(unwrappedItem)

                if let playerItem = unwrappedItem as? PlayerDisplayableWrapper {
                    btDevicesPairedImageView.isHidden = !playerItem.hasBTChildren
                    zbDevicesPairedImageView.isHidden = !playerItem.hasZBChildren
                } else if let playerGroupItem = unwrappedItem as? PlayerGroupDisplayableWrapper {
                    btDevicesPairedImageView.isHidden = !playerGroupItem.hasBTChildren
                    zbDevicesPairedImageView.isHidden = !playerGroupItem.hasZBChildren
                }else {
                    btDevicesPairedImageView.isHidden = true
                    zbDevicesPairedImageView.isHidden = true
                }
            }

        }
    }
    var expanded: Bool = true {
        didSet {
            guard let constraint = bottomViewHeightLayoutConstraint,
                let card = bottomView else {
                    return
            }

            card.isHidden = !expanded
            constraint.constant = 0
            if expanded,
                let unwrappedItem = item {

                let height = Float(unwrappedItem.stateDescription.count) * 20.0 + 20.0
                constraint.constant = CGFloat(height)
            }

        }
    }
}

// MARK: - Overriden methods
extension MasterViewControllerTableViewCell {
    override func awakeFromNib() {
        containerView.layer.cornerRadius = 4
        containerView.clipsToBounds = true
    }
}
        
// MARK: - UI Actions
extension MasterViewControllerTableViewCell {
    @IBAction private func tappedActionButton(_ sender: AnyObject?) {
        delegate?.cell(self, didTapActionForItem: item!)
    }
    
    @IBAction private func tappedOptionButton(_ Sender: AnyObject?) {
        delegate?.cell(self, didTapOptionsButtonForItem: item!)
    }
}

// MARK: - Private
extension MasterViewControllerTableViewCell {
    private func isLastChild(_ testItem: MasterViewControllerDisplayable) -> Bool {
        if let parent = testItem.parent {
            if let index = parent.children.firstIndex(where: { return $0 === testItem }) {
                return index == parent.children.count - 1
            }
            return false
        }
        return false
    }

    private func drawTree(_ item: MasterViewControllerDisplayable) {
        let showLeftIndent = item.depth != 0
        let hasChildren = item.children.count != 0

        indentImageStackView.subviews.forEach { $0.removeFromSuperview() }
        indentImageStackViewWidthLayoutConstraint.constant = 30.0 * CGFloat(item.depth)

        if showLeftIndent {
            for _ in 0..<item.depth {
                indentImageStackView.addArrangedSubview(TreeIndentView())
            }

            if item.depth > 1 {
                // Handle all but last item
                var currentParent = item.parent
                let lastMiddleIndex = Int(item.depth) - 1
                for viewIndex in (0..<lastMiddleIndex).reversed() {
                    if let cp = currentParent {
                        if let view = indentImageStackView.arrangedSubviews[viewIndex] as? TreeIndentView {
                            if isLastChild(cp) {
                                view.shape = .none
                            } else {
                                view.shape = .parent
                            }
                        }
                        currentParent = cp.parent
                    } else {
                        break
                    }
                }
            }

            if let last = indentImageStackView.arrangedSubviews.last as? TreeIndentView {
                if isLastChild(item) {
                    last.shape = .lastChild
                } else {
                    last.shape = .peer
                }
            }
        }

        bottomIndentImage.isHidden = !hasChildren
        bottomIndentImage.shape = .parent
    }

    private func setIcon(_ item: MasterViewControllerDisplayable) {
        switch item.encapsulatedType {
        case .speakerGroup:
            typeImageView.image = UIImage(named: "ic-group")
        case .speaker, .speakerChannel, .speakerConvenienceGroup:
            typeImageView.image = UIImage(named: "ic-speaker")
        case .bluetoothHeadphone:
            typeImageView.image = UIImage(named: "ic-bt-headphones")
        case .zigbeeLight:
            typeImageView.image = UIImage(named: "ic-lightbulb")
        case .zigbeeThermostat:
            typeImageView.image = UIImage(named: "ic-thermostat")
        case .zigbeeOther:
            typeImageView.image = UIImage(named: "ic-zigbee-connected")
        default:
            typeImageView.image = nil
        }
    }
}
