//
//  DispatchQueue+Extension.swift
//  HXSwift
//
//  Created by lizhengyi on 2018/2/24.
//  Copyright © 2018年 lizhengyi. All rights reserved.
//

import UIKit

/*Extension*****************************************************************************/
extension DispatchQueue {
    public static var `default`: DispatchQueue { return DispatchQueue.global(qos: .`default`) }
    public static var userInteractive: DispatchQueue { return DispatchQueue.global(qos: .userInteractive) }
    public static var userInitiated: DispatchQueue { return DispatchQueue.global(qos: .userInitiated) }
    public static var utility: DispatchQueue { return DispatchQueue.global(qos: .utility) }
    public static var background: DispatchQueue { return DispatchQueue.global(qos: .background) }
    
    private static var _onceToken = [String]()
    
    public class func once(_ token: String, block:()->Void) {
        objc_sync_enter(self)
        defer { objc_sync_exit(self) }
        
        if _onceToken.contains(token) {
            return
        }
        _onceToken.append(token)
        block()
    }
    
    public func asyncAfter(_ delay: TimeInterval, execute closure: @escaping () -> Void) {
        self.asyncAfter(deadline: .now() + delay, execute: closure)
    }
    
    public func `repeat`(timeInterval: Double, repeatCount:Int, handler:@escaping (DispatchSourceTimer?, Int)->()) {
        if repeatCount <= 0 {
            return
        }
        let timer = DispatchSource.makeTimerSource(flags: [], queue: self)
        var count = repeatCount
        timer.schedule(wallDeadline: .now(), repeating: timeInterval)
        timer.setEventHandler(handler: {
            count -= 1
            DispatchQueue.main.async {
                handler(timer, count)
            }
            if count == 0 {
                timer.cancel()
            }
        })
        timer.resume()
    }
}

/******************************************************************************End*/

