//
//  History.swift
//  KTester
//
//  Created by Kiril Strax on 2019-09-26.
//  Copyright © 2019 Kiril Strax. All rights reserved.
//

import Foundation

protocol HistoryListener {
    func onChange()
}

class History {

    static let instance = History()

    static let MAX_HISTORY = 10

    var events: [String] {
        return internalEvents
    }

    var summary: String {
        let entries = events.reversed().map { $0 }
        return entries.joined(separator: "\n")
    }

    var listener: HistoryListener? {
        get { return internalListener }
        set { internalListener = newValue }
    }

    private var internalEvents = [String]()
    private var internalListener: HistoryListener?

    func addEvent(event: String) {
        while internalEvents.count >= History.MAX_HISTORY {
            internalEvents.remove(at: 0)
        }
        internalEvents.append(event)
        notifyListener()
    }

    func removeListener() {
        listener = nil
    }

    private init() {
        // singleton
    }

    private func notifyListener() {
        guard let _listener = listener else {
            return
        }
        _listener.onChange()
    }
}
