//
//  UIColor.swift
//  Astro
//
//  Created by Mike Klemarewski on 2015-06-01.
//  Copyright (c) 2015 Mobify Research & Development Inc. All rights reserved.
//

import Foundation

public extension UIColor {
    // Initializer for hex colors with the format "#RRGGBB"
    @objc convenience init?(hex: String) {

        let colorRegex = try!  NSRegularExpression(pattern: "^#[0-9a-f]{6}$", options: .caseInsensitive)
        let colorIsValid = colorRegex.matches(in: hex, options: [], range: NSMakeRange(0, hex.count)).count > 0

        if !colorIsValid {
            return nil
        }

        let redRange    = hex.index(hex.startIndex, offsetBy: 1) ..< hex.index(hex.startIndex, offsetBy: 3)
        let greenRange  = hex.index(hex.startIndex, offsetBy: 3) ..< hex.index(hex.startIndex, offsetBy: 5)
        let blueRange   = hex.index(hex.startIndex, offsetBy: 5) ..< hex.index(hex.startIndex, offsetBy: 7)

        var red: UInt32 = 0
        var green: UInt32 = 0
        var blue: UInt32 = 0

        Scanner(string: hex.substring(with: redRange)).scanHexInt32(&red)
        Scanner(string: hex.substring(with: greenRange)).scanHexInt32(&green)
        Scanner(string: hex.substring(with: blueRange)).scanHexInt32(&blue)

        self.init(
            red: CGFloat(red) / 255,
            green: CGFloat(green) / 255,
            blue: CGFloat(blue) / 255,
            alpha: 1
        )
    }
}
