//
//  KMPageRangePickerWindowController.swift
//  PDF Master
//
//  Created by tangchao on 2022/11/25.
//

import Cocoa

typealias KMPageRangePickerWindowControllerCancelClick = (_ window: NSWindow)->()
typealias KMPageRangePickerWindowControllerConfirmClick = (_ windowController: NSWindowController)->()
class KMPageRangePickerWindowController: NSWindowController {

    @IBOutlet weak var titleLabel: NSTextField!
    
    @IBOutlet weak var allPageButton: NSButton!
    @IBOutlet weak var oddPagesButton: NSButton!
    @IBOutlet weak var evenPagesButton: NSButton!
    @IBOutlet weak var customPagesButton: NSButton!
    
    @IBOutlet weak var customPagesTextField: NSTextField!
    @IBOutlet weak var cancelButton: NSButton!
    @IBOutlet weak var confirmButton: NSButton!
    
    var fileModel: KMMergeFileModel!
    
    var selectIndex: Int = 0
    
    var cancelClick: KMPageRangePickerWindowControllerCancelClick!
    var confirmClick: KMPageRangePickerWindowControllerConfirmClick!
    
    override func windowDidLoad() {
        super.windowDidLoad()

        titleLabel.stringValue = NSLocalizedString("页面范围", comment: "")
        
        allPageButton.title = NSLocalizedString("全部页面", comment: "")
        allPageButton.target = self
        allPageButton.action = #selector(allPageButtonAction)
        
        oddPagesButton.title = NSLocalizedString("奇数页面", comment: "")
        oddPagesButton.target = self
        oddPagesButton.action = #selector(oddPagesButtonAction)
        
        evenPagesButton.title = NSLocalizedString("偶数页面", comment: "")
        evenPagesButton.target = self
        evenPagesButton.action = #selector(evenPagesButtonAction)
        
        customPagesButton.title = NSLocalizedString("自定义", comment: "")
        customPagesButton.target = self
        customPagesButton.action = #selector(customPagesButtonAction)
        
        customPagesTextField.placeholderString = NSLocalizedString("如1,3-5,10", comment: "")
        customPagesTextField.isEnabled = false
        
        cancelButton.title = NSLocalizedString("Cancel", comment: "")
        cancelButton.target = self
        cancelButton.action = #selector(cancelButtonAction)
        confirmButton.title = NSLocalizedString("Confirm", comment: "")
        confirmButton.target = self
        confirmButton.action = #selector(confirmButtonAction)
        
        selectIndex = 0;
        allPageButton.state = .on
    }
    
    @objc func allPageButtonAction() {
        for button in [allPageButton, oddPagesButton, evenPagesButton, customPagesButton] {
            button?.state = .off
        }
        
        allPageButton.state = .on
        window?.makeFirstResponder(nil)
        customPagesTextField.isEnabled = false
        selectIndex = 0
    }
    
    @objc func oddPagesButtonAction() {
        for button in [allPageButton, oddPagesButton, evenPagesButton, customPagesButton] {
            button?.state = .off
        }
        
        oddPagesButton.state = .on
        window?.makeFirstResponder(nil)
        customPagesTextField.isEnabled = false
        selectIndex = 1
    }
    
    @objc func evenPagesButtonAction() {
        for button in [allPageButton, oddPagesButton, evenPagesButton, customPagesButton] {
            button?.state = .off
        }
        
        evenPagesButton.state = .on
        window?.makeFirstResponder(nil)
        customPagesTextField.isEnabled = false
        selectIndex = 2
    }
    
    @objc func customPagesButtonAction() {
        for button in [allPageButton, oddPagesButton, evenPagesButton, customPagesButton] {
            button?.state = .off
        }
        
        customPagesButton.state = .on
        customPagesTextField.isEnabled = true
        window?.makeFirstResponder(customPagesTextField)
        selectIndex = 3
    }
    
    @objc func cancelButtonAction() {
        guard let callback = cancelClick else {
            return
        }
        
        callback(window!)
    }
    
    @objc func confirmButtonAction() {
        if selectIndex == 3 && findSelectPage(pagesString: self.customPagesTextField.stringValue).count == 0 {
            let alert = NSAlert()
            alert.alertStyle = .warning
            alert.messageText = NSLocalizedString("Invalid page range or the page number is out of range. Please try again.", comment: "")
            alert.runModal()
            return
        }
        
        guard let callback = confirmClick else {
            return
        }
        
        callback(self)
    }
    
    func isValidPagesString(pagesString: String)-> Bool {
        var valid = false
        for ch in pagesString {
            if ch != "0" && ch != "1" && ch != "2" && ch != "3" && ch != "4" && ch != "5" && ch != "6" && ch != "7" && ch != "8" && ch != "9" && ch != "," && ch != "-" {
                valid = false
                break
            } else {
                valid = true
            }
        }
        
        return valid
    }
    
    func findSelectPage(pagesString: String) -> ([Int]) {
        if !isValidPagesString(pagesString: pagesString) {
            return []
        }
        
        var result: [Int] = []
        let array = pagesString.components(separatedBy: ",")
        for string in array {
            if string.isEmpty {
                return []
            } else {
                let pages = string .components(separatedBy: "-")
                if pages.count > 2 {
                    return []
                } else if pages.count == 1 {
                    let page = pages[0]
                    if page.isEmpty || Int(page)! > fileModel.document.pageCount || Int(page)! == 0 {
                        return []
                    } else {
                        var hasSame: Bool = false
                        for i in result {
                            if i == Int(page)! {
                                hasSame = true
                                return []
                            }
                        }
                        if !hasSame {
                            result.append(Int(page)!)
                        }
                    }
                } else if pages.count == 2 {
                    let page1 = pages[0]
                    let page2 = pages[1]
                    if page1.isEmpty || page2.isEmpty || page1 >= page2 || Int(page2)! > fileModel.myDocument.pageCount || Int(page1)! == 0 {
                        return []
                    } else {
                        var hasSame: Bool = false
                        for i in Int(page1)! ... Int(page2)! {
                            for j in result {
                                if j == i {
                                    hasSame = true
                                    return []
                                }
                            }
                        }
                        if !hasSame {
                            for i in Int(page1)! ... Int(page2)! {
                                result.append(i)
                            }
                        }
                     }
                }
            }
        }
        
        return result
    }
}