//
/*
 * Copyright (c) 2021 BWI GmbH
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import UIKit
import SwiftUI

@available(iOS 14.0, *)
@objcMembers
class ContentScannerStatusCell: ContentScannerBaseCell {
           
    private var tapRecognizer: UITapGestureRecognizer?
    
    required init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        let view = self.setupInnerContentView()
        self.setupTapRecognizer(view)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupInnerContentView() -> UIView {
        let innerContent = ContentScannerStatus()

        let controller = UIHostingController(rootView:ContentScannerStatusContentView(scanStatus: innerContent))
        
        innerContent.theme = ThemeService.shared().theme
        
        controller.view.backgroundColor = .clear
        //self.bubbleCellContentView?.innerContentView.addSubview(controller.view)
        self.roomCellContentView?.innerContentView.vc_addSubViewMatchingParentSafeArea(controller.view)
        self.innerContent = innerContent
        
        return controller.view
    }
    
    override func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        
        // Recognize touch only if scan status is trusted
        guard gestureRecognizer == self.tapRecognizer, self.scanStatusViewData?.scanStatus == .trusted else {
            return false
        }
        
        return super.gestureRecognizer(gestureRecognizer, shouldReceive: touch)
    }
    
    // MARK: Private
    
    private func setupTapRecognizer(_ view: UIView) {
        let tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:)))
        tapRecognizer.delegate = self
        view.addGestureRecognizer(tapRecognizer)
        self.tapRecognizer = tapRecognizer
    }
    
    @objc private func handleTap(_ gestureRecognizer: UITapGestureRecognizer) {
        guard let scanStatusViewData = self.scanStatusViewData, let delegate = self.delegate else {
            return
        }
        
        if scanStatusViewData.scanStatus == .trusted {
            delegate.cell(self, didRecognizeAction: kMXKRoomBubbleCellTapOnAttachmentView, userInfo: nil)
        }
    }
}
