//
//  lkfAnonymizationTests.swift
//  lkfcTests
//
//  Created by Alexander Holzer on 16.12.23.
//  Copyright © 2023 Alexander Holzer. All rights reserved.
//

import XCTest
@testable import lkfc

final class lkfAnonymizationTests: XCTestCase {

    static let inPath = URL(fileURLWithPath: "\(LKFTest.rootPath)inAno", isDirectory: true)

    
    func createContextWith (model: UInt32, year: Int32? = nil, lines : [String]) throws -> LKFContext {
        let c = try lkfcTests.createContextWith(model:model, lines:lines)
        if let year {
            c.setContextParameters(year: year)
        }
        return c
    }
    
    func testAno() throws {
        let files : [URL]
        do {
            files = try FileManager.default.contentsOfDirectory(at: lkfAnonymizationTests.inPath, includingPropertiesForKeys: nil, options: [])
        }
        catch {
            assert(false, "cannot read input files")
            return
        }
        
        let batchParameters = LKFBatchFileExecutionParametersForTest (outPath: lkfcTests.outPath)
        batchParameters.rootPath = LKFTest.rootPath
        batchParameters.createTestOutput = false
        batchParameters.comparePath = lkfcTests.comparePath
        batchParameters.keepContext = true
        batchParameters.anonymization = LKFAnonymizationSettings(addYears: 2, nextKey: 0)
        var failCount = 0
        var lastFailure : String? = nil
        
        for inputFile in files {
            
            guard !inputFile.lastPathComponent.starts(with: ".") else {
                continue
            }
            
            print ("******* anonymization testdata: \(inputFile)")
            
            let execution = LKFBatchFileExecution(file: inputFile, parameters: batchParameters)
            
            let result = try execution.execute()
            
            if let failure = result as? LKFBatchFileExecutionResultFailed {
                lastFailure = failure.failureTextWithFile
                failCount += 1
            }
            
            if let sourceContext = execution.sourceContext, let targetContext = execution.context {
                let sourceErrors = LKFContextErrors(context: sourceContext)
                let targetErrors = LKFContextErrors(context: targetContext)
                
                if let differences = targetErrors.compare(source: sourceErrors, ignore: ["EK3G", "EX4W","FATL"]) {
                    for d in differences {
                        print (d)
                    }
                    XCTAssert(false, "\(differences.count) error differences for \(inputFile)")
                }
            }
        }
                
        if failCount > 0 {
            if failCount == 1 {
                XCTAssert(false, lastFailure!)
            }
            else {
                XCTAssert(false, "\(failCount) failed, last = \(lastFailure!)")
            }
        }
    }
}
