//
//  KMBatchOperateRemoveWatermarkViewController.swift
//  PDF Reader Pro
//
//  Created by liujiajie on 2023/11/6.
//

import Cocoa
import StoreKit

class KMBatchOperateRemoveWatermarkViewController: KMBatchOperateBaseViewController{
    
    var isBackground: Bool = false
    
    var haveFiles: Bool = false
    
    @IBOutlet var titleLabel: NSTextField!
    
    @IBOutlet var detailLabel: NSTextField!
    
    @IBOutlet var actionButton: NSButton!
    
    @IBOutlet var bottomBaseView: NSView!
    
    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 = self.isBackground ? KMLocalizedString("Remove Background", nil) : KMLocalizedString("Remove Watermark", nil)
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
            } else {
                self.actionButton.tag = 0
                self.actionButton.title = KMLocalizedString("Cancel", nil)
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
            }
        }
        get{
            return super.interfaceStatus
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
        DistributedNotificationCenter.default().removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        localizedLanguage()
        configuUI()
        NotificationCenter.default.addObserver(self, selector: #selector(batchFilesCountNotification(notification:)), name: Notification.Name(rawValue: "KMBatchFilesCountNotification"), object: nil)
//        NotificationCenter.default.addObserver(self, selector: #selector(themeChanged(notification:)), name: Notification.Name(rawValue: "AppleInterfaceThemeChangedNotification"), object: nil)
        DistributedNotificationCenter.default().addObserver(self, selector: #selector(themeChanged(notification:)), name: NSNotification.Name("AppleInterfaceThemeChangedNotification"), object: nil)
    }
    
    @IBAction func buttonClicked_RemoveWatermark(_ sender: NSButton) {
        if !self.haveFiles { return }
        if sender.tag == 1 {
            var hasTask = false
            for i in 0..<(self.files?.count ?? 0) {
                let file = self.files?[i]
                if file?.status == .Waiting && file?.fileType == .PDF {
                    hasTask = true
                    break
                }
            }
            if !hasTask {
                NSSound.beep()
                return
            }
            let openPanel = NSOpenPanel()
            openPanel.canChooseFiles = false
            openPanel.canChooseDirectories = true
            openPanel.canCreateDirectories = true
            openPanel.beginSheetModal(for: self.view.window!) { (result) in
                if result.rawValue == NSApplication.ModalResponse.OK.rawValue {
                    for fileURL in openPanel.urls {
                        self.choosePath = fileURL.path
                        if self.isBackground {
                            self.beginRemoveBackground()
                        } else {
                            self.beginRemoveWatermark()
                        }
                    }
                }
            }
        } else if sender.tag == 0 {
            if self.queue?.operations.count ?? 0 > 0 {
                self.queue?.cancelAllOperations()
            }
            self.interfaceStatus = .PrepareProcess
        }
    }
    @objc func batchFilesCountNotification(notification: Notification) {
        let arr: Array? = notification.object as? [KMBatchOperateFile]
        self.files? = arr ?? []
        if self.files?.count ?? 0 > 0{
            self.haveFiles = true
        } else {
            self.haveFiles = false
        }
        updateBtnStatus()
    }
    @objc func themeChanged(notification: Notification) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            self.updateViewColor()
        }
    }
    
    func updateViewColor() {
        self.view.wantsLayer = true
        if KMAppearance.isDarkMode() {
            self.bottomBaseView.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
            self.view.layer?.backgroundColor = NSColor(red: 0.149, green: 0.157, blue: 0.169, alpha: 1).cgColor
        } else {
            self.bottomBaseView.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1).cgColor
            self.view.layer?.backgroundColor = NSColor(red: 0.988, green: 0.992, blue: 1.000, alpha: 1).cgColor
        }
        self.updateBtnStatus()
    }
    
    func localizedLanguage() {
        self.titleLabel.stringValue = self.isBackground ?  KMLocalizedString("Remove Background", nil) : KMLocalizedString("Remove Watermark", nil)
        self.detailLabel.stringValue = self.isBackground ? KMLocalizedString("The PDF background remover helps you to remove images and color backgrounds from PDF files for an easy reading experience.", nil) : KMLocalizedString("PDF Reader Pro is a PDF watermark remover helping you to remove textual and image watermarks from PDF files. The quality of the final output is same as the original files.", nil)
        self.actionButton.title = self.titleLabel.stringValue
    }
    
    func configuUI() {
        self.view.wantsLayer = true
        self.view.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
        self.titleLabel.font = NSFont.boldSystemFont(ofSize: 14)
        self.detailLabel.font = NSFont.systemFont(ofSize: 12)
        self.titleLabel.textColor = KMAppearance.Layout.h0Color()
        self.detailLabel.textColor = KMAppearance.Layout.h1Color()
        self.actionButton.font = NSFont.systemFont(ofSize: 13)
        self.actionButton.wantsLayer = true
        self.updateBtnStatus()
        self.actionButton.layer?.cornerRadius = 1.0
        
        self.bottomBaseView.wantsLayer = true
        self.bottomBaseView.layer?.backgroundColor = KMAppearance.Layout.l0Color().cgColor
        
        self.updateViewColor()
    }
    
    func updateBtnStatus() {
        if KMAppearance.isDarkMode() {
            if self.files?.count ?? 0  > 0 {
                self.actionButton.layer!.backgroundColor = NSColor(red: 0.306, green: 0.498, blue: 0.859, alpha: 1).cgColor
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
                self.haveFiles = true
            } else {
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color().withAlphaComponent(0.6))
                self.actionButton.layer!.backgroundColor = NSColor(red: 0.306, green: 0.498, blue: 0.859, alpha: 0.6).cgColor
                self.haveFiles = false
            }
        } else {
            if self.files?.count ?? 0 > 0 {
                self.actionButton.layer?.backgroundColor = NSColor(red: 0.153, green: 0.235, blue: 0.384, alpha: 1).cgColor
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color())
                self.haveFiles = true
            } else {
                self.actionButton.setTitleColor(KMAppearance.Layout.w0Color().withAlphaComponent(0.6))
                self.actionButton.layer?.backgroundColor = NSColor(red: 0.153, green: 0.235, blue: 0.384, alpha: 0.6).cgColor
                self.haveFiles = false
            }
        }
    }
    func beginRemoveBackground() {
        self.hiddenWindowCloseButtonIfNeeded()
        self.successFilePathURLArray?.removeAll()
        for i in 0..<(self.files?.count ?? 0) {
            let file = self.files?[i]
            if file?.fileType == .PDF {
                file?.removeBackgroundInfo.savePath = self.choosePath
                if file?.status == .Waiting {
                    let operation = KMBatchRemoveBackgroundOperation(file: file!)
                    operation.delegate = self
                    self.queue?.addOperation(operation)
                }
            }
        }
        if self.queue?.operations.count ?? 0 > 0 {
            self.interfaceStatus = .Processing
        }
    }
    func beginRemoveWatermark() {
        self.hiddenWindowCloseButtonIfNeeded()
        self.successFilePathURLArray?.removeAll()
        for i in 0..<(self.files?.count ?? 0) {
            let file = self.files?[i]
            if file?.fileType == .PDF {
                file?.removeWatermarkInfo.savePath = self.choosePath
                if file?.status == .Waiting {
                    let operation = KMBatchRemoveWatermarkOperation(file: file!)
                    operation.delegate = self
                    self.queue?.addOperation(operation)
                }
            }
        }
        if self.queue?.operations.count ?? 0 > 0 {
            self.interfaceStatus = .Processing
        }
    }
}