//
//  KMBatchOperateCompressViewController.swift
//  PDF Reader Pro
//
//  Created by kdanmobile on 2023/10/31.
//

import Cocoa

class KMBatchOperateCompressViewController: KMBatchOperateBaseViewController{
    
    @IBOutlet var titleLabel: NSTextField!
    
    @IBOutlet var dpi300Button: NSButton!
    
    @IBOutlet var dpi300Label: NSTextField!
    
    @IBOutlet var dpi150Button: NSButton!
    
    @IBOutlet var dpi150Label: NSTextField!
    
    @IBOutlet var dpi72Button: NSButton!
    
    @IBOutlet var dpi72Label: NSTextField!
    
    @IBOutlet var dpi50Button: NSButton!
    
    @IBOutlet var dpi50Label: NSTextField!
    
    @IBOutlet var otherChoiceButton: NSButton!
    
    @IBOutlet var actionButton: NSButton!
    
    @IBOutlet var comprssSlider: KMSlider!
    
    @IBOutlet var lowLabel: NSTextField!
    
    @IBOutlet var highLabel: NSTextField!
    
    var currentType: NSNumber = 60
    var savePath: String?
    var haveFiles: Bool = false
    
    override var interfaceStatus: KMBatchOperateInterfaceStatus?{
        set{
            super.interfaceStatus = newValue
            if newValue == .PrepareProcess {
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
                    let files = NSMutableArray()
                    for url in self.successFilePathURLArray! {
                        if FileManager.default.fileExists(atPath: url.path) {
                            files.add(url)
                        }
                    }
                    if files.count > 0 {
                        let workspace = NSWorkspace.shared
                        workspace.activateFileViewerSelecting(files as! [URL])
                    }
                }
                self.actionButton.tag = 1
                self.actionButton.title = NSLocalizedString("Compress", comment: "")
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
            } else {
                self.actionButton.tag = 0
                self.actionButton.title = NSLocalizedString("Cancel", comment: "")
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
            }
        }
        get{
            return super.interfaceStatus
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        DistributedNotificationCenter.default().removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.localizedLanguage()
        self.configuUI()
        
//        NotificationCenter.default.addObserver(self, selector: #selector(themeChanged(notification:)), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
        DistributedNotificationCenter.default().addObserver(self, selector: #selector(themeChanged(notification:)), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
    }
    func localizedLanguage() {
        self.titleLabel.stringValue = NSLocalizedString("Optimization Options", comment: "")
        self.actionButton.title = NSLocalizedString("Compress", comment: "")
        self.dpi300Label.stringValue = NSLocalizedString("Large File Size(High Quality)", comment: "")
        self.dpi150Label.stringValue = NSLocalizedString("Medium File Size(Medium Quality)", comment: "")
        self.dpi72Label.stringValue = NSLocalizedString("Small File Size(Recommended Quality)", comment: "")
        self.dpi50Label.stringValue = NSLocalizedString("Minimum File Size(Low Quality)", comment: "")
        self.otherChoiceButton.title = NSLocalizedString("Other", comment: "")
        self.lowLabel.stringValue = NSLocalizedString("Low Quality", comment: "")
        self.highLabel.stringValue = NSLocalizedString("High Quality", comment: "")
        self.lowLabel.stringValue = NSLocalizedString("Low Quality", comment: "")
    }
    func configuUI() {
        self.view.wantsLayer = true 
        self.updateViewColor()
        self.dpi300Button.setTitleColor(KMAppearance.Layout.h0Color())
        self.dpi150Button.setTitleColor(KMAppearance.Layout.h0Color())
        self.dpi72Button.setTitleColor(KMAppearance.Layout.h0Color())
        self.dpi50Button.setTitleColor(KMAppearance.Layout.h0Color())
        self.otherChoiceButton.setTitleColor(KMAppearance.Layout.h0Color())
        
        self.currentType = 60
        self.dpi72Button.state = .on
        self.dpi50Button.state = .off
        self.dpi300Button.state = .off
        self.dpi150Button.state = .off
        self.otherChoiceButton.state = .off
        
        self.highLabel.isEnabled = false
        self.lowLabel.isEnabled = false
        self.comprssSlider.isEnabled = false
        self.comprssSlider.tipEnabled = false
        
        self.lowLabel.textColor = KMAppearance.Layout.h0Color()
        self.highLabel.textColor = KMAppearance.Layout.h0Color()
        self.lowLabel.alphaValue = 0.4
        self.highLabel.alphaValue = 0.4
        
        self.actionButton.wantsLayer = true
        if self.files!.count > 0 {
            self.actionButton.layer!.backgroundColor = KMAppearance.Interactive.m0Color().cgColor
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
            self.haveFiles = true
        } else {
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color().withAlphaComponent(0.6))
            self.actionButton.layer!.backgroundColor = KMAppearance.Interactive.m0Color().withAlphaComponent(0.6).cgColor
            self.haveFiles = false
        }
        self.actionButton.layer!.cornerRadius = 1.0
        
        NotificationCenter.default.addObserver(self, selector: #selector(batchFilesCountNotification(notification:)), name: NSNotification.Name("KMBatchFilesCountNotification"), object: nil)
    }
    func updateViewColor() {
        if KMAppearance.isDarkMode() {
            self.view.layer?.backgroundColor = NSColor(red: 0.055, green: 0.067, blue: 0.078, alpha: 1).cgColor
        } else {
            self.view.layer?.backgroundColor = NSColor(red: 0.922, green: 0.925, blue: 0.941, alpha: 1).cgColor
        }
    }
    @objc func themeChanged(notification: Notification) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.updateViewColor()
        }
    }
    @objc func batchFilesCountNotification(notification: Notification) {
        let files: Array? = notification.object as? [KMBatchOperateFile]
        self.files? = files ?? []
        if files!.count > 0 {
            self.actionButton.layer?.backgroundColor = KMAppearance.Interactive.m0Color().cgColor
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
            self.haveFiles = true
        } else {
            self.actionButton.setTitleColor(KMAppearance.Layout.w0Color().withAlphaComponent(0.6))
            self.actionButton.layer!.backgroundColor = KMAppearance.Interactive.m0Color().withAlphaComponent(0.6).cgColor
            self.haveFiles = false
        }
    }
    
    @IBAction func buttonClicked_Action(_ sender: Any) {
        if !self.haveFiles { return }
        //点击开始
        if (sender as AnyObject).tag == 1 {
            self.beginBatchOperation()
        } else if (sender as AnyObject).tag == 0 {
            self.cancelBatchOperation()
        }
    }
    
    @IBAction func comprssVauleAction(_ sender: Any) {
        self.currentType = (comprssSlider.integerValue) as NSNumber;
    }
    
    @IBAction func buttonClicked_ChooseDPI(_ sender: NSButton) {
        self.dpi300Button.state = .off
        self.dpi150Button.state = .off
        self.dpi72Button.state = .off
        self.dpi50Button.state = .off
        self.otherChoiceButton.state = .off
        sender.state = .on
        if sender.tag == 0 {
            self.currentType = 120
        } else if sender.tag == 1 {
            self.currentType = 90
        } else if sender.tag == 2 {
            self.currentType = 60
        } else if sender.tag == 3 {
            self.currentType = 30
        } else {
            self.currentType = (self.comprssSlider.integerValue) as NSNumber
        }
        if sender.tag == 4 {
            highLabel.isEnabled = true
            lowLabel.isEnabled = true
            comprssSlider.isEnabled = true
            comprssSlider.tipEnabled = true
            lowLabel.textColor = KMAppearance.Layout.h0Color()
            highLabel.textColor = KMAppearance.Layout.h0Color()
            self.lowLabel.alphaValue = 1
            self.highLabel.alphaValue = 1
        } else {
            highLabel.isEnabled = false
            lowLabel.isEnabled = false
            comprssSlider.isEnabled = false
            comprssSlider.tipEnabled = false
            lowLabel.textColor = KMAppearance.Layout.h0Color()
            highLabel.textColor = KMAppearance.Layout.h0Color()
            self.lowLabel.alphaValue = 0.4
            self.highLabel.alphaValue = 0.4
        }
    }
    
    override func beginQueueOperation() {
        // hiddenWindowCloseButtonIfNeeded()
        self.successFilePathURLArray?.removeAll()
        for i in 0..<self.files!.count {
            let file = self.files![i]
            if file.fileType == .PDF {
                file.compressInfo.savePath = self.choosePath
                if file.status == .Waiting {
                    let operation = KMCompressOperation.init(file: file, compressValue: self.currentType)
                    operation.delegate = self
                    self.queue?.addOperation(operation)
                }
            }
        }
        if self.queue?.operations.count ?? 0 > 0 {
            self.interfaceStatus = .Processing
        }
    }
}