//
//  LKFDataStructureField.swift
//  LKF
//
//  Created by Alexander Holzer on 28.03.23.
//  Copyright © 2023 Alexander Holzer. All rights reserved.
//

import Foundation
@_implementationOnly import LibLKF

public class LKFRecordTypeField {
    
    public let recordType: LKFRecordType
    public let name: String
    public let type: String
    public let pos: Int?
    public let len: Int?
    public let fieldIndex: Int
    
    public private(set) var check : LKFRecordTypeCheck?
    
    var lkfContext : LKFContext? {
        return recordType.lkfContext
    }
        
    init (recordType: LKFRecordType, name: String, type: String, fieldIndex: Int = -1, pos: Int?, len: Int?) {
        self.recordType = recordType
        self.name = name
        self.type = type
        self.pos = pos
        self.len = len
        self.fieldIndex = fieldIndex
    }
    
    convenience init? (recordType: LKFRecordType, satzarten: OpaquePointer, satzartIndex: UInt32, fieldIndex: UInt32, lineBuffer: UnsafeMutablePointer<CChar>) {
        
        guard LibLKF.lkf_Satzart_getSatzartFieldInfo(satzarten, satzartIndex, fieldIndex, lineBuffer, 1024) != 0 else {
            return nil
        }
        
        let parts = String(cString:lineBuffer).components(separatedBy: ";")
        
        guard parts.count >= 8 else {
            return nil
        }
        
        let name = parts[7].trimmingCharacters(in: .whitespaces)
        let type = parts[3].trimmingCharacters(in: .whitespaces)
        let pos = Int(parts[4].trimmingCharacters(in: .whitespaces))
        let len = Int(parts[5].trimmingCharacters(in: .whitespaces))
        
        self.init(recordType: recordType, name: name, type: type, fieldIndex: Int(fieldIndex), pos: pos, len: len)
        
        if let lkfContext, let checkInfo = LibLKF.lkf_Satzart_getSatzartFieldCheck (lkfContext.ptr!, satzarten, satzartIndex, fieldIndex) {
            self.check = LKFRecordTypeCheck(field: self, checkInfo: checkInfo, lineBuffer: lineBuffer)
        }
        else {
            self.check = nil
        }
    }
    
    func change (check: LKFRecordTypeCheck?) {
        self.check = check
    }
    
    public func checksFor (errorCode: String) -> [LKFRecordTypeCheck]? {
        return check?.checksFor(errorCode: errorCode)
    }


}
