//
//  LKFFileImportFilter.swift
//  LKF
//
//  Created by Alexander Holzer on 11.09.24.
//  Copyright © 2024 Alexander Holzer. All rights reserved.
//

import Foundation


public class LKFFileImportFilterCondition {
    public let key : String
    
    public init (key: String) {
        self.key = key
    }
    
    open func isIncluded(line: String, lineParts:[String]? = nil) -> Bool {
        return true
    }
}

public class LKFFileImportFilterCategory : LKFFileImportFilterCondition {
    
    public let activeOptions: Set<String>
    public let converter: ((_:[String]) -> String?)
    
    public init (key: String, activeOptions: Set<String>, converter: @escaping ((_:[String]) -> String?)) {
        self.activeOptions = activeOptions
        self.converter = converter
        super.init(key: key)
    }
    
    public convenience init? (analyserCategory: LKFFileAnalyserCategory) {
        
        if analyserCategory.activeIndices != 0 {
            var stringSet = Set<String>()
            for i in 0..<analyserCategory.options.count {
                if (analyserCategory.activeIndices & (1<<i)) != 0 {
                    stringSet.insert (analyserCategory.options[i].value)
                }
            }
            self.init(key: analyserCategory.key, activeOptions: stringSet, converter: analyserCategory.converter)
        }
        else {
            return nil
        }
    }
    
    open override func isIncluded(line: String, lineParts:[String]? = nil) -> Bool {
        let lineParts = lineParts ?? line.components(separatedBy: "|")
        guard let v = converter(lineParts), activeOptions.contains(v) else {
            return false
        }
        return true
    }
}


public class LKFFileImportFilter {
    let conditions: [LKFFileImportFilterCondition]
    
    public init (conditions: [LKFFileImportFilterCondition]) {
        self.conditions = conditions
    }
    
    public convenience init? (analyser: LKFFileAnalyser) {
        var importerCategories = [LKFFileImportFilterCategory]()
        for c in analyser.categories {
            guard let cat = LKFFileImportFilterCategory(analyserCategory: c) else {
                continue
            }
            importerCategories.append(cat)
        }
        guard importerCategories.count > 0 else {
            return nil
        }
        self.init(conditions: importerCategories)
    }
    
    
    public func isIncluded(line: String, lineParts:[String]? = nil) -> Bool {
        let lineParts = lineParts ?? line.components(separatedBy: "|")
        for c in conditions {
            if !c.isIncluded(line: line, lineParts: lineParts) {
                return false
            }
        }
        return true
    }
}
