//
//  LKFContextStammProvider.swift
//  lkfc
//
//  Created by Alexander Holzer on 12.08.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import Foundation

public class LKFContextStammProvider {

    var _linesToAdd = [String:[String]]()
    var _fileNamePaths = [String:String]()
    
    var _currentArray : [String]?
    var _currentIndex = 0
    
    static var current : LKFContextStammProvider?
    
    init() {
        LKFContextStammProvider.current = self
    }

    public func setFilePath (file: String, fullPath: String) {
        _fileNamePaths[file.lowercased()] = fullPath
    }
    
    public func add (file: String, line: String) {
        
        let lowerCaseFile = file.lowercased()
        
        if _linesToAdd[lowerCaseFile] != nil {
            _linesToAdd[lowerCaseFile]!.append(line)
        }
        else {
            _linesToAdd[lowerCaseFile] = [line]
        }
    }
    
    var callback : @convention(c) (Optional<OpaquePointer>, Optional<UnsafePointer<Int8>>) -> Optional<UnsafePointer<Int8>> =
    { (context, filename) -> Optional<UnsafePointer<Int8>> in
        
        if let sp = LKFContextStammProvider.current {
            if filename != nil {
                let f = String(cString:filename!).lowercased()
                sp._currentIndex = 0;
                sp._currentArray = sp._linesToAdd [f]
            }
            if (sp._currentArray != nil && sp._currentArray!.count > sp._currentIndex) {
                sp._currentIndex += 1
                return (sp._currentArray![sp._currentIndex - 1] as NSString).utf8String
            }
        }
        return nil
    }
    
    var fileCallback : @convention(c) (Optional<OpaquePointer>, Optional<UnsafePointer<Int8>>) -> Optional<UnsafePointer<Int8>> =
    { (context, filename) -> Optional<UnsafePointer<Int8>> in
    
        if filename != nil, let sp = LKFContextStammProvider.current,
            let fullPath = sp._fileNamePaths[String(cString:filename!).lowercased()] {
            return (fullPath as NSString).utf8String
        }
        return nil
    }
}
