//
//  LKFIssueSumList.swift
//  lkfc
//
//  Created by Alexander Holzer on 06.06.22.
//  Copyright © 2022 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFSumIssueList {
    
    public let context : LKFContext
    
    public var issues = [LKFSumIssue]()
    
    public init (context: LKFContext) {
        self.context = context
        self.load()
    }
    
    public func load() {
    
        let min = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
        let max = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
        let cString = UnsafeMutablePointer<CChar>.allocate(capacity: 512)
        
        LibLKF.lkf_getErrorCodeMinMax(context.ptr, min, max)
        
        for i in min.pointee...max.pointee {
            let count = LibLKF.lkf_context_errorcode_count (context.ptr, 0, i)
            if count > 0 {
                LibLKF.lkf_getErrorCodeFromInt (i, cString)
                if let codeString = String(cString: cString, encoding: .utf8) {
                    if let cText = LibLKF.lkf_plaus_ErrorCode2Text(context.ptr, Int32(i)) {
                        let text = String(cString: cText, encoding: .utf8) ?? "not utf8"
                        issues.append(LKFSumIssue(errorCode: "EX\(codeString)", errorText: text, count: Int(count)))
                    }
                }
            }
        }

        LibLKF.lkf_getWarningCodeMinMax(context.ptr, min, max)
        
        for i in min.pointee...max.pointee {
            let count = LibLKF.lkf_context_errorcode_count (context.ptr, 0, i)
            if count > 0 {
                LibLKF.lkf_getErrorCodeFromInt (i, cString)
                if let codeString = String(cString: cString, encoding: .utf8) {
                    if let cText = LibLKF.lkf_plaus_ErrorCode2Text(context.ptr, Int32(i)) {
                        let text = String(cString: cText, encoding: .utf8) ?? "not utf8"
                        issues.append(LKFSumIssue(errorCode: "WX\(codeString)", errorText: text, count: Int(count)))
                    }
                }
            }
        }

        cString.deallocate()
        min.deallocate()
        max.deallocate()
        
    }
}
