//
//  LKFOutputFileStat.swift
//  lkfc
//
//  Created by Alexander Holzer on 08.07.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFOutputStatFile : 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)
        for statType : UInt32 in 0...3 {
            LibLKF.lkf_stat_getHeadline(context.ptr!, statType, lineBuffer, 2048)
            outputStrings.append(String(cString:lineBuffer))
            
            let count = lkf_stat_getLineCount (context.ptr!, statType);
            
            for i in 0..<count
            {
                lkf_stat_getLine (context.ptr!, statType, i, lineBuffer, 2048);
                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.x\(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()
    }
}
