//
//  KMToolCompareWindowController.swift
//  PDF Reader Pro
//
//  Created by liujiajie on 2023/11/9.
//

import Cocoa

var currentWindowController: KMToolCompareWindowController? = nil

@objcMembers class KMToolCompareWindowController: NSWindowController, NSWindowDelegate{
    var type: KMCompareWithToolType?
    
    lazy var payConvertCompareViewController: KMConvertComparePayViewController? = {
        let Com = KMConvertComparePayViewController(select: self.selectIndex)
        
        Com?.block = { type in
            if type == .restore {
                IAPProductsManager.default().restoreSubscriptions()
                self.addWaingView(view: self.window?.contentView ?? NSView())
            } else if type == .refresh {
                VerificationManager().verification(complention: { (status, info, error) in
                    if let error = error {
                        let alert = NSAlert()
                        alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
                        alert.alertStyle = .warning
                        alert.messageText = NSLocalizedString("Failed to Refresh", comment: "")
                        alert.runModal()
                    }
                    self.reloadData()
                    self.removeWaitingView(view: self.window?.contentView ?? NSView())
                })
                
                self.addWaingView(view: self.window?.contentView ?? NSView())
            } else if type == .STORE {
                IAPProductsManager.default().make(IAPProductsManager.default().pdfToOfficeProduct)
                self.addWaingView(view: self.window?.contentView ?? NSView())
            } else if type == .DMG {
                self.officeVerificationBuy()
            }
        }
        return Com
    }()
    
    lazy var convertCompareViewController: KMConvertCompareViewController? = {
        let Com = KMConvertCompareViewController(compareType: self.type?.rawValue ?? 0, select: self.selectIndex)
        
        Com?.block = { type in
            if type == .compare {
                if #available(macOS 10.13, *) {
                    self.close()
                }
//                KMPurchaseCompareWindowController.sharedInstance().startModal("")
            } else if type == .license {
                self.close()
                if VerificationManager.default().status == .none {
                    let vc = KMVerificationWindowController.verification(with: .trial)
                    vc?.showWindow(nil)
                } else {
                    let vc = KMVerificationWindowController.verification(with: .activate)
                    vc?.callback = { [weak self] in
#if VERSION_DMG
                        KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
#else
                        if IAPProductsManager.default().isAvailableAllFunction() {
                            let vc = KMToolCompareWindowController.toolCompare(toolType: self?.type ?? .Convert, selectNum: self?.selectIndex ?? 0)
                            vc.showWindow(nil)
                        } else {
                            KMPurchaseCompareWindowController.sharedInstance().showWindow(nil)
                        }
#endif
                    }
                    vc?.showWindow(nil)
                }
            } else if type == .restore {
                IAPProductsManager.default().restoreSubscriptions()
                self.addWaingView(view: self.window?.contentView ?? NSView())
            } else if type == .month {
                IAPProductsManager.default().make(IAPProductsManager.default().newlyMonthProduct)
                self.addWaingView(view: self.window?.contentView ?? NSView())
            } else if type == .oneTime {
#if VERSION_DMG
                self.verificationBuy()
#else
                IAPProductsManager.default().make(IAPProductsManager.default().allAccessProduct)
                self.addWaingView(view: self.window?.contentView ?? NSView())
#endif
            }
        }
        return Com
    }()

    var selectIndex: Int = 0

    @IBOutlet var box: NSBox!

    var modalSession: NSApplication.ModalSession?
    
    deinit {
#if VERSION_DMG
#else
        NotificationCenter.default.removeObserver(self)
#endif
    }
    
    convenience init(toolType: KMCompareWithToolType, selectNum: Int) {
        self.init(windowNibName: "KMToolCompareWindowController")
        self.type = toolType
        self.selectIndex = selectNum
    }
    
   class func toolCompare(toolType:KMCompareWithToolType, selectNum:Int) -> KMToolCompareWindowController {
        if (currentWindowController != nil) {
            return currentWindowController!
        }
        let vc = KMToolCompareWindowController(toolType: toolType, selectNum: selectNum)
        currentWindowController = vc
        return vc
    }
    
    override func windowDidLoad() {
        super.windowDidLoad()
#if VERSION_DMG
        IAPProductsManager.default().loadProducts()
       
#endif
        NotificationCenter.default.addObserver(self, selector: #selector(IAPProductLoadedNotification(notification:)), name: NSNotification.Name(NSNotification.Name.KMIAPProductLoaded.rawValue), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(IAPSubscriptionLoadedNotification(notification:)), name: NSNotification.Name(NSNotification.Name.KMIAPSubscriptionLoaded.rawValue), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(IAPProductPurchasedNotification(notification:)), name: NSNotification.Name(NSNotification.Name.KMIAPProductPurchased.rawValue), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(IAPProductFailedNotification(notification:)), name: NSNotification.Name(NSNotification.Name.KMIAPProductFailed.rawValue), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(IAPProductRestoreFinishedNotification(notification:)), name: NSNotification.Name(NSNotification.Name.KMIAPProductRestoreFinished.rawValue), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(IAPProductRestoreFailedNotification(notification:)), name: NSNotification.Name(NSNotification.Name.KMIAPProductRestoreFailed.rawValue), object: nil)
        self.window?.backgroundColor = NSColor(red: 36.0/255.0, green:37.0/255.0, blue:39.0/255.0, alpha:1.0)
        self.window?.isMovableByWindowBackground = true

        if type == .Convert {
            self.window?.title = NSLocalizedString("PDF to Office", comment: "")
            
            if IAPProductsManager.default().isAvailableAllFunction() {
                self.setContentView(self.payConvertCompareViewController?.view ?? NSView())
            } else {
                self.setContentView(self.convertCompareViewController?.view ?? NSView())
            }
            self.window?.backgroundColor = KMAppearance.Upgrade.vipBGColor()
        } else if type == .OCR {
            self.window?.title = NSLocalizedString("OCR", comment: "")
            self.setContentView(self.convertCompareViewController?.view ?? NSView())
        } else if type == .PageEdit {
            self.window?.title = NSLocalizedString("Page Edit", comment: "")
            self.setContentView(self.convertCompareViewController?.view ?? NSView())
        } else if type == .PDFEdit {
            self.window?.title = NSLocalizedString("PDF Editor", comment: "")
            self.setContentView(self.convertCompareViewController?.view ?? NSView())
        } else if type == .FromSign || type == .Sign {
            self.window?.title = NSLocalizedString("Form & Sign", comment: "")
            self.setContentView(self.convertCompareViewController?.view ?? NSView())
        } else if type == .EditPDF {
            self.window?.title = NSLocalizedString("Edit PDF", comment: "")
            self.setContentView(self.convertCompareViewController?.view ?? NSView())
        }
    }
    
    override func showWindow(_ sender: Any?) {
        if currentWindowController == nil {
            currentWindowController = self
        }
        super.showWindow(sender)
    }
    
    func windowWillClose(_ notification: Notification) {
        if currentWindowController != nil {
            currentWindowController = nil
            payConvertCompareViewController?.removeObserver()
            payConvertCompareViewController = nil
            convertCompareViewController?.removeObserver()
            convertCompareViewController = nil
        }
    }
    
    func windowShouldClose(_ sender: NSWindow) -> Bool {
        endModal(sender)
        return true
    }
    
    override func close() {
        super.close()
        endModal(nil)
    }
    
    @IBAction func endModal(_ sender: Any?) {
        if let modalSession = self.modalSession {
            NSApp.stopModal()
            NSApp.endModalSession(modalSession)
            self.window?.orderOut(self)
            
            self.modalSession = nil
        }
    }
    @IBAction func startModal(_ sender: Any) {
        NSApp.stopModal()
        
        var modalCode: Int
        self.modalSession = NSApp.beginModalSession(for: self.window!)
        repeat {
            modalCode = (NSApp.runModalSession(modalSession!)).rawValue
        } while modalCode == NSApplication.ModalResponse.continue.rawValue
    }
   
    
    func removeWaitingView(view: NSView) {
        for subview in view.subviews {
            if subview is WaitingView {
                subview.removeFromSuperview()
                break
            }
        }
    }
    
    func setContentView(_ view: NSView) {
        var frame: NSRect = self.window?.frame ?? .zero
        frame.origin.y -= view.frame.size.height - frame.size.height;
        frame.origin.x -= (view.frame.size.width - frame.size.width) / 2.0;
        frame.size.width = view.frame.size.width;
        frame.size.height = view.frame.size.height;
        self.box.contentView = view
        self.window?.setFrame(frame, display: true, animate: true)
    }
    
    func reloadData() {
        if IAPProductsManager.default().isAvailableAllFunction() {
            self.payConvertCompareViewController?.reloadData()
        } else {
            self.convertCompareViewController?.reloadData()
        }
    }
    
    func verificationBuy() {
#if VERSION_DMG
        var url = URL(string: "https://www.pdfreaderpro.com/store?utm_source=MacAppDmg&utm_campaign=StoreLink&utm_medium=PdfStore")
        if SKInspectPublicTool.currentisLanguageHans() {
            url = URL(string: "https://www.pdfreaderpro.com/zh-cn/store?utm_source=MacAppDmg&utm_campaign=StoreLink&utm_medium=PdfStore")
        }
        NSWorkspace.shared.open(url!)
#endif
    }
    
    func officeVerificationBuy() {
#if VERSION_DMG
        var url = URL(string: "https://www.pdfreaderpro.com/store?product_code=product_2&utm_source=MacAppDmg&utm_campaign=OfficeStoreLink&utm_medium=PdfOfficeStore")
        if SKInspectPublicTool.currentisLanguageHans() {
            url = URL(string: "https://www.pdfreaderpro.com/zh-cn/store?product_code=product_2&utm_source=MacAppDmg&utm_campaign=OfficeStoreLink&utm_medium=PdfOfficeStore")
        }
        NSWorkspace.shared.open(url!)
        FMTrackEventManager.defaultManager.trackOnceEvent(event: "PUW", withProperties: ["PUW_Btn":"Btn_PUW_PDFtoOffice_Buy"])
#endif
    }
    
    func showWindowRestore(sender: Any) {
        self.showWindow(sender)
        IAPProductsManager.default().restoreSubscriptions()
        self.addWaingView(view: self.window?.contentView ?? NSView())
    }
    func addWaingView(view: NSView) {
        self.removeWaitingView(view: view)
        let wView = WaitingView(frame: view.bounds)
        wView.autoresizingMask = [.width, .height]
        view.addSubview(wView)
        wView.startAnimation()
    }
 
    @objc func IAPProductFailedNotification(notification: NSNotification) {
        self.removeWaitingView(view: (self.window?.contentView)!)
    }
  
    @objc func IAPProductPurchasedNotification(notification: NSNotification) {
        self.removeWaitingView(view: (self.window?.contentView)!)
        self.reloadData()
    }
    
    @objc func IAPProductLoadedNotification(notification: NSNotification) {
        self.reloadData()
    }

    @objc func IAPProductRestoreFinishedNotification(notification: NSNotification) {
        self.removeWaitingView(view: (self.window?.contentView)!)
        self.reloadData()
    }
  
    @objc func IAPProductRestoreFailedNotification(notification: NSNotification) {
        self.removeWaitingView(view: (self.window?.contentView)!)
    }
   
    @objc func IAPSubscriptionLoadedNotification(notification: NSNotification) {
        self.removeWaitingView(view: (self.window?.contentView)!)
        self.reloadData()
    }
   
}