//
//  lkfcSpecialFiles.swift
//  lkfcTests
//
//  Created by Alexander Holzer on 31.10.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import XCTest
@testable import lkfc

class lkfcSpecialFiles: XCTestCase {

    static let inSpecPath = URL(fileURLWithPath: "\(LKFTest.rootPath)inspec", isDirectory: true)
    
    override func setUp() {
        // Put setup code here. This method is called before the invocation of each test method in the class.
    }

    override func tearDown() {
        // Put teardown code here. This method is called after the invocation of each test method in the class.
    }
    
    func fileNames (at: URL, forExtension: String) -> [URL]? {
        var files = [URL]()
        
        let lowerExt = forExtension.lowercased()
        
        do {
            let allFiles = try FileManager.default.contentsOfDirectory(at: at, includingPropertiesForKeys: nil, options: [])
            for f in allFiles {
                if f.isFileURL && f.pathExtension.lowercased() == lowerExt {
                    files.append(f)
                }
            }
        }
        catch {
            XCTAssert(false, "cannot read input files")
            return nil
        }
        
        return files
    }

    func testAmb0 () {
        if let files = fileNames(at: lkfcSpecialFiles.inSpecPath, forExtension:"amb0") {
            let batchParameters = LKFBatchFileExecutionParametersForTest (outPath: lkfcTests.outPath)
            batchParameters.rootPath = LKFTest.rootPath
            batchParameters.createTestOutput = false
            batchParameters.keepContext = true

            var failCount = 0
            var lastFailure : String? = nil
            
            for inputFile in files {
                let execution = LKFBatchFileExecution(file: inputFile, parameters: batchParameters)
                do {
                    let result = try execution.execute()
                    if let failure = result as? LKFBatchFileExecutionResultFailed {
                        lastFailure = failure.failureTextWithFile
                        failCount += 1
                    }
                    else if let context = result.execution.context {
                        let aufenthaltCount = context.getAufenthaltCount()
                        for i in 0..<aufenthaltCount {
                            let aufenthalt = context[i]
                            if aufenthalt.isAmbulant {
                                XCTAssert(aufenthalt.gesvd == 0, "AUFID=\(aufenthalt.key): ambulant, GESVD = \(aufenthalt.gesvd)")
                            }
                        }
                    }
                }
                catch {
                    lastFailure = error.localizedDescription
                    failCount += 1
                }
            }
            XCTAssert(lastFailure == nil, lastFailure!)
        }
     }
}
