//
//  LKFBatchFileMultiThreadedExecution.swift
//  lkfc
//
//  Created by Alexander Holzer on 12.06.18.
//  Copyright © 2018 Alexander Holzer. All rights reserved.
//

import Foundation

public class LKFBatchFileMultiThreadedExecution : LKFBatchFileExecutionBackgroundProtocol {
    
    var executions = [LKFBatchFileExecution]()
    var _results = [LKFBatchFileExecutionResult]()
    var semaphore : DispatchSemaphore?
    var resultSemaphore = DispatchSemaphore(value: 1)
    
    public init() {
        
    }
    
    public func add (execution: LKFBatchFileExecution) {
        executions.append(execution)
    }
    
    public func execute() {
        
        semaphore = DispatchSemaphore(value: executions.count)
        for e in executions {
            semaphore!.wait()
            e.threadExecute(delegate: self)
        }
        
        for _ in executions {
            semaphore!.wait()
        }
        
        for _ in executions {
            semaphore!.signal()
        }
        
        semaphore = nil
    }
    
    public func execute(chunkSize: Int) {
        semaphore = DispatchSemaphore(value: executions.count)
        for e in executions {
            semaphore!.wait()
            e.threadExecutePackaged(chunkSize: chunkSize, delegate: self)
        }
        
        for _ in executions {
            semaphore!.wait()
        }
        
        for _ in executions {
            semaphore!.signal()
        }
        
        semaphore = nil

    }
    
    public func finished (batchFileResult: LKFBatchFileExecutionResult) {
        resultSemaphore.wait()
        _results.append(batchFileResult)
        resultSemaphore.signal()
        semaphore!.signal()
    }
    
    public var results: [LKFBatchFileExecutionResult] {
        return _results
    }
}
