//
//  KMRightSideViewController.swift
//  PDF Master
//
//  Created by Niehaoyu on 2022/10/26.
//

import Cocoa

enum RightSubViewType : Int {
    case None
    case CipherTextType
    case EditPDFAddText
    case EditPDFAddImage
    case AnnotationProperts
    case Bates
    case Headerfooter
    case Background
    case Watermark
    case ViewSettings
}

typealias KMRightSidePropertyDidChange = (_ model: AnyObject?) -> ()
class KMRightSideViewController: NSViewController,CipherTextViewDelegate {

    var cipherTextView : CipherTextView!
    var eidtPDFTextProperty : KMEditPDFTextPropertyViewController!
    var eidtPDFImageProperty : KMEditImagePropertyViewController!
    var annotationProperties : KMAnnotationPropertiesViewController!
    var listView : CPDFListView!
    var _subViewType : RightSubViewType?
    @IBOutlet weak var contextBox: NSBox!
    var emptyVC : KMRightSideEmptyVC!
    var emptyVC_link: KMLinkAnnotationPropertyEmptyController?
    var _isHidden: Bool = false
    
    var propertyDidChange: KMRightSidePropertyDidChange!
    var model: AnyObject?
    
    weak var delegate: KMEditImagePropertyViewControllerDelegate?
    weak var mainController: KMMainViewController?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do view setup here.
        
//        self.view.wantsLayer = true
//        self.view.layer?.backgroundColor = NSColor.red.cgColor
        emptyVC = KMRightSideEmptyVC.init(nibName: "KMRightSideEmptyVC", bundle: nil)
        contextBox.contentView = emptyVC.view
        self.emptyVC_link = KMLinkAnnotationPropertyEmptyController()
    }
    
    public func reloadDataWithPDFView(pdfView:CPDFListView,isShow:Bool) {
        if self.annotationProperties == nil {
          self.subViewType = .AnnotationProperts
        }
        if(!isShow) {
            self.isHidden = true
            return
        }
        self.annotationProperties.pdfView = pdfView
        var selectedAnnotation : CPDFAnnotation? = nil
        var activeAnnotations : [CPDFAnnotation] = []
        if pdfView.activeAnnotations != nil && pdfView.activeAnnotations.count > 0 {
            selectedAnnotation = pdfView.activeAnnotations.firstObject as? CPDFAnnotation
            for annotation in pdfView.activeAnnotations {
                activeAnnotations.append(annotation as! CPDFAnnotation)
            }
        }
       
        let annotationType = pdfView.annotationType
        if KMAnnotationPropertiesViewController.height(with: selectedAnnotation) > 0 {
            self.annotationProperties.annotations = activeAnnotations
            self.isHidden = !(activeAnnotations.count > 0)
        } else if self.listView.toolMode == .noteToolMode && KMAnnotationPropertiesViewController.height(withAnnotationMode: pdfView.annotationType) > 0 {
            self.isHidden = false
            if pdfView.activeAnnotation is CPDFLinkAnnotation {
                if activeAnnotations.count > 0 {
                    self.annotationProperties.annotations = activeAnnotations
                } else {
                    self.annotationProperties.annotations = []
                    self.annotationProperties.annotationMode = annotationType
                }
            } else {
                self.annotationProperties.annotations = []
                self.annotationProperties.annotationMode = annotationType
            }
        } else if listView.toolMode == .formToolMode && KMAnnotationPropertiesViewController.height(withAnnotationMode: pdfView.annotationType) > 0 {
            self.isHidden = false
            self.annotationProperties.annotations = []
            self.annotationProperties.annotationMode = annotationType
        }  else if listView.toolMode == .selfSignMode && KMAnnotationPropertiesViewController.height(withAnnotationMode: pdfView.annotationType) > 0 {
            self.isHidden = false
            self.annotationProperties.annotations = []
            self.annotationProperties.annotationMode = annotationType
        } else {
            self.isHidden = true
        }
        
        if (self.isHidden) {
            self.annotationProperties.isEmptyAnnotation = self.isHidden
        } else {
            var isShowEmpty = self.isHidden;
            for annotation in activeAnnotations {
                if (annotation is CPDFSignatureAnnotation) || (annotation is CPDFStampAnnotation) {
                    if (annotation is CPDFStampAnnotation) {
                        if (annotation is CSelfSignAnnotation) {
                            break
                        }
                    }
                    isShowEmpty = true;
                    break
                }
            }
            if annotationType == .link && activeAnnotations.count == 0 {
                self.isHidden = true
            } else if (annotationType == .stamp || annotationType == .signSignature) && isShowEmpty {
                let continuousAddStamp = UserDefaults.standard.bool(forKey: "KMContinuousAdditionStamp")
                if continuousAddStamp {
                    isShowEmpty = false
                    self.annotationProperties.isContinuousAddStamp = true
                    
                    UserDefaults.standard.setValue(false, forKey: "KMContinuousAdditionStamp")
                    UserDefaults.standard.synchronize()
                }
            } else {
                if isShowEmpty {
                    
                } else {
                    if _subViewType == RightSubViewType.AnnotationProperts {
                        self.contextBox.contentView = self.annotationProperties.view
                    }
                }
            }
            self.annotationProperties.isEmptyAnnotation = isShowEmpty
        }
    }
    
    //MARK: Setter && Get
    var subViewType : RightSubViewType? {
        set {
            _subViewType = newValue
            if _subViewType == RightSubViewType.CipherTextType {
                self.initCipherTextView()
            } else if _subViewType == RightSubViewType.EditPDFAddText{
                self.initEditPDFTextPropertyViewController()
            } else if _subViewType == RightSubViewType.EditPDFAddImage{
                self.initEditPDFImagePropertyViewController()
            } else if _subViewType == RightSubViewType.AnnotationProperts {
                self.initAnnotationProperts()
            } else if _subViewType == .Bates {
                self.initBatesViewController()
            } else if subViewType == .Headerfooter {
                self.initHeaderFooterViewController()
            } else if subViewType == .Background {
                self.initBackgroundViewController()
            } else if subViewType == .Watermark {
                self.initWatermarkViewController()
            } else if subViewType == .ViewSettings {
                self.initViewSettingsViewController()
            }
        }
        get {
            return _subViewType
        }
    }
    
    var isHidden: Bool {
        get {
            return _isHidden
        }
        set {
            _isHidden = newValue
            if _isHidden {
                if (self.listView.annotationType == .link) {
                    self.contextBox.contentView = self.emptyVC_link?.view
                } else {
                    self.contextBox.contentView = emptyVC.view
                }
            }
        }
    }
    
    //MARK: InitSubViews
    func removeSubViews() {
        
    }
    
    private func initEditPDFTextPropertyViewController() {
        _ = KMEditPDFTextManager.manager.updateTextFontNames(listView: self.listView)
        self.eidtPDFTextProperty = KMEditPDFTextPropertyViewController()
        self.eidtPDFTextProperty.listView = self.listView
        self.eidtPDFTextProperty.view.frame = self.view.bounds
        self.eidtPDFTextProperty.view.autoresizingMask = [.height]
        self.contextBox.contentView =  self.eidtPDFTextProperty.view
    }
    
    private func initEditPDFImagePropertyViewController() {
        self.eidtPDFImageProperty = KMEditImagePropertyViewController()
        self.eidtPDFImageProperty.listView = self.listView
        self.eidtPDFImageProperty.delegate = self
        self.eidtPDFImageProperty.view.frame = self.view.bounds
        self.eidtPDFImageProperty.view.autoresizingMask = [.height]
        self.contextBox.contentView =  self.eidtPDFImageProperty.view
    }
    
    private func initCipherTextView() {
        self.cipherTextView = CipherTextView.createFromNib()
        self.cipherTextView.frame = self.view.bounds
        self.cipherTextView.autoresizingMask = [.height]
        self.cipherTextView.setUp()
        self.contextBox.contentView =  self.cipherTextView
    }
    
    private func initAnnotationProperts() {
        self.annotationProperties = KMAnnotationPropertiesViewController()
        self.annotationProperties.view.frame = self.view.bounds
        self.annotationProperties.pdfView = self.listView
        self.annotationProperties.view.autoresizingMask = [.height,.maxXMargin]
        self.contextBox.contentView = self.annotationProperties.view
        if self.listView.toolMode == .noteToolMode || self.listView.toolMode == .formToolMode
            || self.listView.toolMode == .selfSignMode {
            self.reloadDataWithPDFView(pdfView: self.listView, isShow: true)
        }
    }
    
    var curcontroller: NSViewController?
    private func initBatesViewController() {
//        let controller = KMBatesPropertyHomeController()
//        controller.pageCount = Int(self.listView.document.pageCount)
//        controller.view.frame = self.view.bounds
//        controller.view.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
//        self.contextBox.contentView = controller.view
//        curcontroller = controller
//        
//        controller.modelDidChange = { [weak self] model in
//            guard let callback = self?.propertyDidChange  else {
//                return
//            }
//            
//            self!.model = model
//            callback(model)
//        }
        let Controller: KMBatchOperateAddHeaderFooterViewController = KMBatchOperateAddHeaderFooterViewController(files: [])
        Controller.onlyManagerTemplate = true
        Controller.isBatchOperation = false
        Controller.pdfView = self.listView
        Controller.isBatchOperation = false
        Controller.isBates = true
//        self.titleLabel.stringValue = KMLocalizedString("Manage Templates", nil)
        self.contextBox.contentView? = Controller.view
        curcontroller = Controller
        Controller.view.mas_makeConstraints { make in
            make?.edges.equalTo()(self.view)
        }
    }
    
    private func initHeaderFooterViewController() {
//        let controller = KMHeaderFooterPropertyMainController()
//        controller.pageCount = Int(self.listView.document.pageCount)
//        controller.view.frame = self.view.bounds
//        controller.view.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
//        self.contextBox.contentView = controller.view
//        curcontroller = controller
//        
//        controller.modelDidChange = { [weak self] model in
//            guard let callback = self?.propertyDidChange  else {
//                return
//            }
//            
//            self!.model = model
//            callback(model)
//        }
        let headerFooterViewController: KMBatchOperateAddHeaderFooterViewController = KMBatchOperateAddHeaderFooterViewController(files: [])
        headerFooterViewController.onlyManagerTemplate = true
        headerFooterViewController.isBatchOperation = false
        headerFooterViewController.pdfView = self.listView
//        self.titleLabel.stringValue = KMLocalizedString("Manage Templates", nil)
        self.contextBox.contentView? = headerFooterViewController.view
        curcontroller = headerFooterViewController
        headerFooterViewController.view.mas_makeConstraints { make in
            make?.edges.equalTo()(self.view)
        }
    }
    
    private func initBackgroundViewController() {
//        let controller = KMBackgroundPropertyHomeController()
//        controller.preView = self.listView
//        controller.view.frame = self.view.bounds
//        controller.view.autoresizingMask = NSView.AutoresizingMask(rawValue: 18)
//        self.contextBox.contentView = controller.view
//        
//        controller.modelDidChange = {
//            [weak self] (model: KMBackgroundModel?) -> () in
//            guard let callback = self?.propertyDidChange  else {
//                return
//            }
//            
//            self!.model = model
//            callback(model)
//        }
        let Controller: KMBatchOperateAddWatermarkViewController = KMBatchOperateAddWatermarkViewController(files: [])
        Controller.onlyManagerTemplate = true
        Controller.isBatchOperation = false
        Controller.pdfView = self.listView
        Controller.isBackground = true
        self.contextBox.contentView? = Controller.view
//        self.titleLabel.stringValue = KMLocalizedString("Manage Templates", nil)
        curcontroller = Controller
        Controller.view.mas_makeConstraints { make in
//            make?.left.equalTo()(self.view)
//            make?.right.equalTo()(self.view)
//            make?.bottom.equalTo()(self.view)
//            make?.top.equalTo()(self.view)?.offset()(40)
            make?.edges.equalTo()(self.view)
        }
    }
    
    private func initWatermarkViewController() {
        let addWatermarkViewController: KMBatchOperateAddWatermarkViewController = KMBatchOperateAddWatermarkViewController(files: [])
        addWatermarkViewController.onlyManagerTemplate = true
        addWatermarkViewController.isBatchOperation = false
        addWatermarkViewController.pdfView = self.listView
        self.contextBox.contentView? = addWatermarkViewController.view
//        self.titleLabel.stringValue = KMLocalizedString("Manage Templates", nil)
        curcontroller = addWatermarkViewController
        addWatermarkViewController.view.mas_makeConstraints { make in
//            make?.left.equalTo()(self.view)
//            make?.right.equalTo()(self.view)
//            make?.bottom.equalTo()(self.view)
//            make?.top.equalTo()(self.view)?.offset()(40)
            make?.edges.equalTo()(self.view)
        }
    }
    
    private func initViewSettingsViewController() {
        annotationProperties = KMAnnotationPropertiesViewController()
        annotationProperties.view.frame = self.view.bounds
        annotationProperties.view.autoresizingMask = [.height,.maxXMargin]
        annotationProperties.mainController = mainController
        annotationProperties.pdfView = listView
        annotationProperties.openPropertiesType = .pageDisplay
        annotationProperties.pageDisplayReaderMode = { [weak self] isReaderMode in
            guard let self = self else { return }
            mainController!.readMode(self)
        }
        annotationProperties.isEmptyAnnotation = false
        contextBox.contentView = self.annotationProperties.view
    }
    
    //MARK: CipherTextViewDelegate
    func cipherTextViewButtonClicked(textView: CipherTextView, buttonIndex: Int) {
        if buttonIndex == 0 {
            
        }
    }
    
}

extension KMRightSideViewController: KMEditImagePropertyViewControllerDelegate {
    func editImagePropertyViewControllerDidChanged(controller: KMEditImagePropertyViewController, type: KMEditImagePropertyViewControllerChangeType) {
        self.delegate?.editImagePropertyViewControllerDidChanged(controller: controller, type: type)
    }
}