//
//  MaskMaker.swift
//  map_preprocessor
//
//  Created by Dan Crosby on 6/7/19.
//  Copyright © 2019 Dan Crosby. All rights reserved.
//

import Foundation
import Cocoa

func MasksForProvinces(idMap: [UInt8], provinceIds: [UInt8]) -> Dictionary<UInt8, CGImage> {
    var maskArrays = Dictionary<UInt8, [UInt8]>()

    let group = DispatchGroup()
    let syncQ = DispatchQueue(label: "sync")

    for id in provinceIds {
        DispatchQueue.global().async(group: group) {
            print("starting for province \(id)")
            var arr = [UInt8](repeating: 0, count: idMap.count)
            for index in 0..<idMap.count {
                if idMap[index] == id {
                    arr[index] = 0xFF
                }
            }

            syncQ.sync {
                maskArrays[id] = arr
            }
        }
    }

    group.wait()

    var images = Dictionary<UInt8, CGImage>()

    for (id, arr) in maskArrays {
        images[id] = CGImage(
            width: width,
            height: height,
            bitsPerComponent: 8,
            bitsPerPixel: 8,
            bytesPerRow: width,
            space: CGColorSpace(name: CGColorSpace.linearGray)!,
            bitmapInfo: CGBitmapInfo(),
            provider: CGDataProvider(data: NSData(bytes: arr, length: arr.count))!,
            decode: nil,
            shouldInterpolate: false,
            intent: CGColorRenderingIntent.defaultIntent
            )!
    }

    return images
}
