//
//  LKFMetaData.swift
//  LKF
//
//  Created by Alexander Holzer on 14.01.22.
//  Copyright © 2022 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFMetaData {
    
    let context : LKFContext
    var mels = [String:LKFMetaDataMel]()
    var diags = [String:LKFMetaDataDiag]()
    
    var _allMels : [LKFMetaDataMel]?
    var _allDiags : [LKFMetaDataDiag]?
    
    public init (context: LKFContext) {
        self.context = context
    }
    
    public func mel (for melText: String) -> LKFMetaDataMel? {
        if let m = mels[melText] {
            return m
        }
        
        if let ptr = context.ptr {
            let index = LibLKF.lkf_stamm_getMelIndex (ptr, melText.cString(using: .utf8))
            if index >= 0 {
                let mel = LKFMetaDataMel(context: context, melIndex: UInt32(index))
                mels[melText] = mel
                return mel
            }
        }
        
        return nil
    }
    
    public func diag (for diagText: String) -> LKFMetaDataDiag? {
        if let d = diags[diagText] {
            return d
        }
        
        if let ptr = context.ptr {
            let index = LibLKF.lkf_stamm_getDiagIndex (ptr, diagText.cString(using: .utf8))
            if index >= 0 {
                let diag = LKFMetaDataDiag(context: context, diagIndex: UInt32(index))
                diags[diagText] = diag
                return diag
            }
        }
        
        return nil
    }
    
    public func allDiags() -> [LKFMetaDataDiag]? {
        if let _allDiags {
            return _allDiags
        }
        
        if let ptr = context.ptr {
            let diagCount = LibLKF.lkf_stamm_getDiagCount (ptr)
            if diagCount > 0 {
                var arr = [LKFMetaDataDiag]()
                for i in 0..<UInt32 (diagCount) {
                    arr.append(LKFMetaDataDiag(context: context, diagIndex: i))
                }
                _allDiags = arr
                return _allDiags
            }
        }
        return nil
    }
    
    public func allMels() -> [LKFMetaDataMel]? {
        if let _allMels {
            return _allMels
        }
        if let ptr = context.ptr {
            let melCount = LibLKF.lkf_stamm_getMelCount(ptr)
            if melCount > 0 {
                var arr = [LKFMetaDataMel]()
                for i in 0..<UInt32(melCount) {
                    arr.append(LKFMetaDataMel(context: context, melIndex: i))
                }
                _allMels = arr
                return _allMels
            }
        }
        return nil
    }
    
    public func errorText (for code: String) -> String? {
        
        guard let errorDefList = context.errorDefList else {
            return nil
        }
        guard let errorDef = errorDefList.error(for: code) else {
            return nil
        }
        return errorDef.text
    }
}
