//
//  LKFTest.swift
//  lkfc
//
//  Created by Alexander Holzer on 14.06.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFTest {
    
    static let rootPath = "/Users/alexanderholzer/lkf/test/"
    static let inPath = URL(fileURLWithPath: "\(rootPath)in", isDirectory: true)
    static let outPath = "\(rootPath)out"
    
    public init() {
        
    }
    
    
    public func executeTestData () -> Bool {
        let files : [URL]
        do {
            files = try FileManager.default.contentsOfDirectory(at: LKFTest.inPath, includingPropertiesForKeys: nil, options: [])
        }
        catch {
            assert(false, "cannot read input files")
            return false
        }
        guard let outPathUrl = URL(string: LKFTest.outPath) else {
            return false
        }
        let batchParameters = LKFBatchFileExecutionParametersForTest (outPath: outPathUrl)
        batchParameters.rootPath = LKFTest.rootPath
        var failCount = 0
        
        for inputFile in files {
            
            let execution = LKFBatchFileExecution(file: inputFile, parameters: batchParameters)
            do {
                let result = try execution.execute()
                if  result as? LKFBatchFileExecutionResultFailed != nil {
                    failCount += 1
                }
            }
            catch {
                failCount += 1
            }
            
        }
        
        if failCount > 0 {
            return false
        }
        return true
    }

    
    func handleTestContext (_ testContext: UnsafeMutablePointer<LKF_TESTCONTEXT>) -> [String]? {
        let count = LibLKF.lkf_test_getIssueCount(testContext)
        
        if (count == 0) {
            LibLKF.lkf_free_testcontext(testContext)
            return nil
        }
        
        var issues = [String]()
        
        for i in 0..<count {
            issues.append(String(cString:LibLKF.lkf_test_getIssue(testContext, i)))
        }
        
        LibLKF.lkf_free_testcontext(testContext)
        return issues
    }
    
    public func executeTestUtils () -> [String]? {
        let unsafePath = (LKFTest.rootPath as NSString).utf8String
        if let testContext = LibLKF.lkf_alloc_testcontext(unsafePath) {
            LibLKF.lkf_test_utils(testContext)
            return handleTestContext(testContext)
        }
        return ["cannot create test context"]
    }
    
    public func executeTestAufenthalt () -> [String]? {
        let unsafePath = (LKFTest.rootPath as NSString).utf8String
        if let testContext = LibLKF.lkf_alloc_testcontext(unsafePath) {
            LibLKF.lkf_test_aufenthalt1(testContext)
            return handleTestContext(testContext)
        }
        return ["cannot create test context"]
    }
}
