//
//  LKFErrorDefList.swift
//  LKF
//
//  Created by Alexander Holzer on 27.03.23.
//  Copyright © 2023 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFErrorDefList {
    
    public let errors : [LKFErrorDef]
    let dict : [String:LKFErrorDef]?
    
    public init (lkfContext: LKFContext) {
     
        var arr = [LKFErrorDef]()
        
        guard let ptr = lkfContext.ptr else {
            errors = []
            dict = nil
            return
        }
        
        let lineBuffer = UnsafeMutablePointer<CChar>.allocate(capacity:2048)
        
        let pList = LibLKF.lkf_create_errorinfo (ptr, 0xFFFFFFFF)
        LibLKF.lkf_errorinfo_getHeadline (pList, lineBuffer, 1024);

        let errorcount = LibLKF.lkf_errorinfo_getCount (pList);
        
        for i in 0..<errorcount
        {
            let pErrorInfo = LibLKF.lkf_errorinfo_getError (pList, i);
            LibLKF.lkf_errorinfo_getErrorLine (pErrorInfo, lineBuffer, 1024);
            
            if let errorDef = LKFErrorDef(line: String(cString:lineBuffer)) {
                arr.append(errorDef)
            }
        }
        
        LibLKF.lkf_free_errorinfo (pList);
        
        lineBuffer.deallocate()
        
        var dict = [String:LKFErrorDef]()
        for e in arr {
            dict[e.code] = e
        }
        self.dict = dict
        self.errors = arr.sorted(by: { $0.code < $1.code })
    }
    
    public func error (for code: String) -> LKFErrorDef? {
        return dict?[code]
    }
}
