//
//  LKFOutputNPTraceFile.swift
//  lkfc
//
//  Created by Alexander Holzer on 16.09.24.
//  Copyright © 2024 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFOutputNPTraceFile : LKFOutputFilePackaged {
    
    var firstPackage = true
    
    public override init (context: LKFContext) {
        super.init(context: context)
    }
    
    public func createOutput() -> [String] {
        var outputStrings = [String]()
        let lineBuffer = UnsafeMutablePointer<CChar>.allocate(capacity:2048)

        LibLKF.lkf_npplaus_getProtokollHeadline(context.ptr!, lineBuffer, 2048)
        outputStrings.append(String(cString:lineBuffer))

        let count = LibLKF.lkf_npplaus_getWarningLineCount (context.ptr!)
        
        for i in 0..<count {
            LibLKF.lkf_npplaus_getWarningLine (context.ptr!, i, lineBuffer, 1024);
            outputStrings.append(String(cString:lineBuffer))
            LibLKF.lkf_npplaus_getInfoLine (context.ptr!, i, lineBuffer, 1024);
            outputStrings.append(String(cString:lineBuffer))
            
            let tfcount = LibLKF.lkf_npplaus_getReasonCount (context.ptr!, i)
            for j in 0..<tfcount {
                LibLKF.lkf_npplaus_getReasonLine (context.ptr!, i, j, lineBuffer, 1024);
                outputStrings.append(String(cString:lineBuffer))

            }
        }
        
        let protocollCount = LibLKF.lkf_npplaus_getProtokollLineCount (context.ptr!)
        for i in 0..<protocollCount {
            LibLKF.lkf_npplaus_getProtokollLine (context.ptr!, i, lineBuffer, 1024);
            outputStrings.append(String(cString:lineBuffer))
        }
        
        lineBuffer.deallocate()
        return outputStrings
    }
    
    public override func getOutput() throws -> [String] {
        
        if let packagedOutput = super.output {
            return packagedOutput
        }
        
        try context.executeStat()
        return createOutput()
    }
    
    public override var defaultfileName : String {
        return "\(context.KANR)j001.ntrace\(context.model%100)"
    }
    
    public override func packageExecuted () {
        if firstPackage {
            LibLKF.lkf_stat(context.ptr!)
            firstPackage = false
        }
        else {
            LibLKF.lkf_stat_package(context.ptr!)
        }
    }

    public override func executionEnd () {
        _output = createOutput()
    }
}


