//
//  KMPurchaseLimitWindowController.swift
//  Cisdem PDFMaster
//
//  Created by Niehaoyu on 2023/11/20.
//

import Cocoa

class KMPurchaseLimitWindowController: NSWindowController {

    @IBOutlet weak var contendView: NSView!
    @IBOutlet weak var infoContendView: NSView!
    @IBOutlet weak var titleLbl: NSTextField!
    @IBOutlet weak var subTitleLabel: NSTextField!
    @IBOutlet weak var infoTitleLabel: NSTextField!
    @IBOutlet weak var desLabel1: NSTextField!
    @IBOutlet weak var desLabel2: NSTextField!
    @IBOutlet weak var desLabel3: NSTextField!
    
    @IBOutlet weak var purchaseBox: NSBox!
    @IBOutlet weak var purchaseBtn: KMButton!
    
    @IBOutlet weak var convertButton: HyperLinkButton!
    
    @objc var continueBlock: ((_ limitWC: KMPurchaseLimitWindowController)->Void)?
    
    //MARK: 打开文件
    @objc static func currentLimitWC() -> KMPurchaseLimitWindowController {
        if let controller: KMPurchaseLimitWindowController = KMPurchaseLimitWindowController.fetchSampleController() {
            return controller
        } else {
            let purchaseLimitWC: KMPurchaseLimitWindowController = KMPurchaseLimitWindowController.init(windowNibName: "KMPurchaseLimitWindowController")
            return purchaseLimitWC
        }
    }
    
    static func fetchSampleController() -> KMPurchaseLimitWindowController? {
        for window in NSApp.windows {
            let controller = window.windowController
            if controller is KMPurchaseLimitWindowController {
                return controller as? KMPurchaseLimitWindowController
            }
        }
        
        return nil
    }
    
    deinit {
        DistributedNotificationCenter.default().removeObserver(self)
    }
    
    override func windowDidLoad() {
        super.windowDidLoad()

        // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
        
        DistributedNotificationCenter.default().addObserver(self, selector: #selector(themeChange), name: NSNotification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil)

        self.refreshUI()
        
        
    }
    
    func refreshUI() {
        
        self.contendView.wantsLayer = true
        
        self.titleLbl.stringValue = NSLocalizedString("Purchase PDF to Office Pack", comment: "")
        self.subTitleLabel.stringValue = NSLocalizedString("Convert first 10 pages only. Purchase PDF to Office Pack to convert all pages.", comment: "")
        self.infoTitleLabel.stringValue = NSLocalizedString("PDF to Office Pack Benefits", comment: "")
        self.desLabel1.stringValue = NSLocalizedString("Unlimited PDF file conversion", comment: "")
        self.desLabel2.stringValue = NSLocalizedString("Get converted files in high quality", comment: "")
        self.desLabel3.stringValue = NSLocalizedString("Batch Convert PDFs", comment: "")
        
        self.subTitleLabel.textColor = KMAppearance.Layout.h0Color()
        self.infoTitleLabel.textColor = KMAppearance.Layout.h0Color()
        self.desLabel1.textColor = KMAppearance.Layout.h0Color()
        self.desLabel2.textColor = KMAppearance.Layout.h0Color()
        self.desLabel3.textColor = KMAppearance.Layout.h0Color()
        
        self.titleLbl.font = NSFont.UbuntuBoldFontWithSize(21)
        self.subTitleLabel.font = NSFont.SFProTextRegularFont(14)
        self.infoTitleLabel.font = NSFont.SFMediumFontWithSize(16)
        self.desLabel1.font = NSFont.SFProTextRegularFont(14)
        self.desLabel2.font = NSFont.SFProTextRegularFont(14)
        self.desLabel3.font = NSFont.SFProTextRegularFont(14)
        
        
        self.purchaseBox.wantsLayer = true
        self.purchaseBox.cornerRadius = CGRectGetHeight(self.purchaseBox.frame)/2
        self.purchaseBox.layer?.masksToBounds = true
        
        self.purchaseBtn.wantsLayer = true
        self.purchaseBtn.layer?.cornerRadius = CGRectGetHeight(self.purchaseBtn.frame)/2.0
        self.purchaseBtn.layer?.masksToBounds = true
        self.purchaseBtn.title = NSLocalizedString("Upgrade", comment: "")
        self.purchaseBtn.setTitleColor(NSColor.white)
        self.purchaseBtn.mouseMoveCallback = { mouseEntered in
            if mouseEntered {
                self.purchaseBtn.layer?.backgroundColor = NSColor.black.withAlphaComponent(0.15).cgColor
            } else {
                self.purchaseBtn.layer?.backgroundColor = NSColor.clear.cgColor
            }
        }
//        self.purchaseBtn.setTitleFont(NSFont.UbuntuBoldFontWithSize(16)
        
        self.convertButton.title = NSLocalizedString("Refresh Purchase Status", comment: "")
        self.convertButton.mouseMoveCallback = { mouseEntered in
            if mouseEntered {
                if KMAppearance.isDarkMode() {
                    self.convertButton.setTitleColor(NSColor.white)
                } else {
                    self.convertButton.setTitleColor(NSColor(red: 8/255.0, green: 124/255.0, blue: 255/255.0, alpha: 1))
                }
            } else {
                if KMAppearance.isDarkMode() {
                    self.convertButton.setTitleColor(NSColor(red: 181/255.0, green: 179/255.0, blue: 231/255.0, alpha: 1))
                } else {
                    self.convertButton.setTitleColor(NSColor(red: 0, green: 33/255.0, blue: 67/255.0, alpha: 1))
                }
            }
        }
        
        self.updateViewColor()
    }
    
    func updateViewColor() {
        if KMAppearance.isDarkMode() {
            self.contendView.layer?.backgroundColor = NSColor(red: 24/255.0, green: 22/255.0, blue: 31/255.0, alpha: 1).cgColor
            self.titleLbl.textColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1)
            self.convertButton.setTitleColor(NSColor(red: 181/255.0, green: 179/255.0, blue: 231/255.0, alpha: 1))
        } else {
            self.contendView.layer?.backgroundColor = NSColor(red: 247/255.0, green: 245/255.0, blue: 1, alpha: 1).cgColor
            self.titleLbl.textColor = NSColor(red: 0, green: 33/255.0, blue: 67/255.0, alpha: 1)
            self.convertButton.setTitleColor(NSColor(red: 0, green: 33/255.0, blue: 67/255.0, alpha: 1))
        }
    }
    
    func addWaingView(_ view: NSView) {
        self.removeWaitingView(view)
        
        let wView = WaitingView.init(frame: view.bounds)
        wView.autoresizingMask = [.width, .height]
        view.addSubview(wView)
        wView.startAnimation()
        
    }
    
    func removeWaitingView(_ view: NSView) {
        let views = NSArray.init(array: view.subviews)
        for subView in views {
            if (subView as AnyObject).isKind(of: WaitingView.self) {
                (subView as AnyObject).removeFromSuperview()
            }
        }
    }
    
    //MARK: IBAction
    @IBAction func unlimitConvertAction(_ sender: Any) {
        var tStrUrl = "https://www.cisdem.com/pdfmaster-mac/buy.html"
        let defs = UserDefaults.standard
        if let languages = defs.object(forKey: "AppleLanguages") as? [String], let preferredLang = languages.first {
            if preferredLang.hasPrefix("de") {
                tStrUrl = "https://www.cisdem.com/de/pdfmaster-mac/buy.html"
            } else if preferredLang.hasPrefix("fr") {
                tStrUrl = "https://www.cisdem.com/fr/pdfmaster-mac/buy.html"
            } else if preferredLang.hasPrefix("it") {
                tStrUrl = "https://www.cisdem.com/it/pdfmaster-mac/buy.html"
            } else if preferredLang.hasPrefix("es") {
                tStrUrl = "https://www.cisdem.com/es/pdfmaster-mac/buy.html"
            } else if preferredLang.hasPrefix("pt") {
                tStrUrl = "https://www.cisdem.com/pt/pdfmaster-mac/buy.html"
            } else if preferredLang.hasPrefix("ja") {
                tStrUrl = "https://www.cisdem.com/jp/pdfmaster-mac/buy.html"
            }
        }
        guard let url = URL(string: tStrUrl) else {
            return
        }
        NSWorkspace.shared.open(url)
        FMTrackEventManager.defaultManager.trackOnceEvent(event: "PUW", withProperties: ["PUW_Btn":"Btn_PUW_PDFtoOffice_Buy"])
    }
    
    @IBAction func continueConvertAction(_ sender: Any) {
        VerificationManager.default().verification { status, info, error in
            if (error != nil) {
                let alert = NSAlert.init()
                alert.messageText = NSLocalizedString("Failed to Refresh", comment: "")
                alert.addButton(withTitle: NSLocalizedString("OK", comment: ""))
                alert.runModal()
            }
            self.removeWaitingView(self.contendView)
            
            if IAPProductsManager.default().isAvailableAdvancedPDFToOffice() {
                self.close()
            }
        }
        self.addWaingView(self.contendView)
    }
    
    @objc func themeChange() {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3) {
            self.updateViewColor()
        }
    }
}