//
//  NXBaseBubbleView.swift
//  bubbleLayer_swift
//
//  Created by liuming on 2020/8/23.
//  Copyright © 2020 liuming. All rights reserved.
//

import Foundation
import UIKit
public class NXNormalBubbleView: NXInteractiveView {
    let bubbleLayer = NXBubbleLayer(originalSize: .zero)
    var currentLayer: CALayer?
    /// 内部内容控件
    public var containView = NXBubbleContainView(frame: .zero)

    // 矩形的圆角的半径
    public var cornerRadius: CGFloat = 8
    // 箭头位置的圆角半径
    public var arrowRadius: CGFloat = 3
    // 箭头的高度
    public var arrowHeight: CGFloat = 12
    // 箭头的宽度
    public var arrowWidth: CGFloat = 30
    // 箭头方向
    public var arrowDirection: ArrowDirection = .bottom
    // 箭头的相对位置
    public var arrowPosition: CGFloat = 0.5

    public var bubbleColor: UIColor = .white {
        didSet {
            self.setNeedsLayout()
            self.layoutIfNeeded()
        }
    }

    override public init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(containView)
    }

    required init?(coder _: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override public func layoutSubviews() {
        super.layoutSubviews()
        if let layer = currentLayer {
            layer.removeFromSuperlayer()
        }
        bubbleLayer.size = frame.size
        bubbleLayer.cornerRadius = cornerRadius
        bubbleLayer.arrowRadius = arrowRadius
        bubbleLayer.arrowHeight = arrowHeight
        bubbleLayer.arrowWidth = arrowWidth
        bubbleLayer.arrowDirection = arrowDirection
        bubbleLayer.arrowPosition = arrowPosition
        let layer = bubbleLayer.layer()
        layer.fillColor = bubbleColor.cgColor
        self.layer.insertSublayer(layer, at: 0)
        currentLayer = layer
        // 调整 contain坐标
        containView.frame = bubbleLayer.bubbleLayerRect

        backgroundColor = .clear
        containView.backgroundColor = .clear
    }

    // MARK: - 重写交互层的长按和点击事件

    override public func tapGestureRecognizerHandler(sender: UITapGestureRecognizer) {
        super.tapGestureRecognizerHandler(sender: sender)
        print("点击了普通气泡")
    }

    override public func longGestureRecognizerHandler(sender: UILongPressGestureRecognizer) {
        super.longGestureRecognizerHandler(sender: sender)
        print("长按了 点击了普通气泡")
    }
}
