import UIKit
import LinkPresentation

// swiftlint: disable force_unwrapping
// swiftlint: disable force_cast
class LinkPreviewChatTableViewCell: BaseChatTableViewCell {
    var linkView: UIView? {
        didSet {
            if let value = oldValue {
                if #available(iOS 13.0, *) {
                    (value as! LPLinkView).metadata = LPLinkMetadata()
                }
                value.removeFromSuperview()
            }
            if let value = linkView {
                self.contentView.addSubview(value)
                NSLayoutConstraint.activate([
                    value.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 2),
                    value.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -4),
                    value.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 44),
                    value.trailingAnchor.constraint(lessThanOrEqualTo: self.contentView.trailingAnchor, constant: -22)
                ])
            }
        }
    }

    func set(linkPreview item: ChatLinkPreview, indexPath: IndexPath) {
        super.set(item: item, indexPath: indexPath)
        if #available(iOS 13.0, *) {
            var metadata = MetadataCache.instance.metadata(for: "\(item.id)")
            var isNew = false
            let url = URL(string: item.url)!

            if (metadata == nil) {
                metadata = LPLinkMetadata()
                metadata!.originalURL = url
                isNew = true
            }
            // if self.linkView == nil {
            self.linkView = LPLinkView(url: url)
            linkView?.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
            linkView?.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
            linkView?.translatesAutoresizingMaskIntoConstraints = false
            // }

            let linkView = self.linkView as! LPLinkView
            linkView.metadata = metadata!

            if isNew {
                MetadataCache.instance.generateMetadata(for: url, withId: "\(item.id)", completionHandler: { meta1 in
                    guard meta1 != nil else {
                        return
                    }
                    DBChatHistoryStore.instance.itemUpdated(withId: item.id, for: item.account, with: item.jid)
                })
            }
        }
    }
}
