//
//  LKFOutputDataFile.swift
//  lkfc
//
//  Created by Alexander Holzer on 07.06.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFOutputDataFile : LKFOutputFilePackaged {
    
    public var createOutputForTest = false
    
    public override init (context: LKFContext) {
        super.init(context: context)
    }
    
    public override func getOutput() -> [String] {
        let count = LibLKF.lkf_get_aufenthalt_anz(context.ptr!)
        
        var outputStrings = [String]()
        
        if createOutputForTest {
            outputStrings.append("#version=0.1")
            outputStrings.append("#model=\(context.model);year=\(context.period);flags=\(context.flags)")
            if let path = context.metaDataContext?.baseUrl {
                outputStrings.append("#path=\(path.path())")
            }
        }
        
        let addLineCount = LibLKF.lkf_getaddlineanz(context.ptr!)
        
        var postStrings = [String]()
        let lineBuffer = UnsafeMutablePointer<CChar>.allocate(capacity:2048)

        for i in 0..<addLineCount {
            LibLKF.lkf_getaddline(context.ptr, i, lineBuffer)
            let s = String(cString:lineBuffer)
            if s.hasPrefix("K01") {
                outputStrings.append(s)
            }
            else {
                postStrings.append(s)
            }
        }
        lineBuffer.deallocate()
        for i in 0..<count {
            let aufenthalt = LKFAufenthalt(context:context, index:i)
            let lines = aufenthalt.getOutput()
            outputStrings.append(contentsOf: lines)
            if createOutputForTest {
                let testLines = aufenthalt.getTestOutput()
                outputStrings.append(contentsOf: testLines)
            }
        }
        
        for s in postStrings {
            outputStrings.append(s)
        }
        
        return outputStrings
    }
    
    public override var defaultfileName : String {
        
        if createOutputForTest {
            return "\(context.KANR)j001.t\(context.model%100)"
        }
        return "\(context.KANR)j001.s\(context.model%100)"
    }
}
