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

import Foundation
@_implementationOnly import LibLKF

public class LKFOutputNPSumFile : 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_sum_headline (context.ptr!, lineBuffer, 512)
        outputStrings.append(String(cString:lineBuffer))

        let count = LibLKF.lkf_npplaus_sum_abtcount (context.ptr!)

        for i in 0..<count {
            if (LibLKF.lkf_npplaus_sum_abtline (context.ptr!, i, lineBuffer, 512) != nil) {
                outputStrings.append(String(cString:lineBuffer))
            }
        }

        LibLKF.lkf_npplaus_tfsum_headline (context.ptr!, lineBuffer, 512)
        outputStrings.append(String(cString:lineBuffer))

        for i in 0..<count {
            LibLKF.lkf_npplaus_tfsum (context.ptr!, i, lineBuffer, 512)
            outputStrings.append(String(cString:lineBuffer))
        }

        LibLKF.lkf_npplaus_critsum_headline (context.ptr!, lineBuffer, 512)
        outputStrings.append(String(cString:lineBuffer))

        for i in 0..<count {
            LibLKF.lkf_npplaus_critsum (context.ptr!, i, lineBuffer, 512)
            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)np\(context.model%100).csv"
    }
    
    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()
    }
}

