//
//  LKFLine.swift
//  lkfc
//
//  Created by Alexander Holzer on 20.08.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import Foundation


public enum LKFRecordTypeChange {
    case insert
    case delete
    case update
}

public class LKFLine {
    public let _line: String
    public var lineIdent: String
    private var _splittedLine : [String]?
    private var _changedSplittedLine : [String]?
    public private(set) var changeType: LKFRecordTypeChange?
    
    public init(_ line: String, lineIdent: String? = nil) {
        _line = line
        if lineIdent == "insert" {
            changeType = .insert
            self.lineIdent = ""
        }
        else {
            self.lineIdent = lineIdent ?? ""
        }
    }
    
    public init (type: String, aufenthalt: LKFAufenthalt, content: String? = nil) {
        changeType = .insert
        _line = aufenthalt.createLine (with: type, content: content)
        self.lineIdent = ""
    }
    
    public func copy() -> LKFLine {
        return LKFLine(updatedLine, lineIdent: "insert")
    }
    
    public var splittedLine : [String] {
        if (_splittedLine == nil) {
            _splittedLine = _line.components(separatedBy: "|")
        }
        return _splittedLine!
    }
    
    public func valueAt (index: Int) -> String {
        let sl = _changedSplittedLine ?? splittedLine
        if index < sl.count {
            return sl[index]
        }
        return ""
    }
    
    public func valueAt (field: LKFRecordTypeField) -> String {
        return valueAt(index: field.fieldIndex + 1)
    }
    
    public var line : String {
        return _line
    }
    
    public var updatedLine: String {
        guard let _changedSplittedLine else {
            return line
        }
        return _changedSplittedLine.joined(separator: "|")
    }
    
    public func set (value: String, at pos: Int) {
        if _changedSplittedLine == nil {
            _changedSplittedLine = splittedLine
        }
        if _changedSplittedLine!.count > pos {
            _changedSplittedLine![pos] = value
            return
        }
        while _changedSplittedLine!.count <= pos {
            _changedSplittedLine!.append("")
        }
        _changedSplittedLine![pos] = value
        self.changeType = .update
    }
    
    public func delete () {
        self.changeType = .delete
    }
    
    public func dismissChanges() {
        self.changeType = nil
        self._changedSplittedLine = nil
    }
}
