//
// Validator.m
// GotoBus
//
// Created by haibara on 2/15/15.
//
//

#import "Validator.h"

@implementation Validator
@end

@implementation GenericValidator

+ (BOOL)matchRegexp:(NSString *)value regexp:(NSString *)regexp {
	return [value rangeOfString:regexp options:NSRegularExpressionSearch].location != NSNotFound;
}

+ (BOOL)isEmail:(NSString *)value {
	NSTextCheckingResult *firstMatchResult = [[NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:NULL] firstMatchInString:value options:0 range:NSMakeRange(0, value.length)];
	return [firstMatchResult.URL isKindOfClass:[NSURL class]] && [firstMatchResult.URL.scheme isEqualToString:@"mailto"];
}

+ (BOOL)isInRange:(CGFloat)value min:(CGFloat)min max:(CGFloat)max {
	return value >= min && value <= max;
}

@end

@interface CreditCardValidator ()
@property (nonatomic, assign) CreditCardType options;
@end

@implementation CreditCardValidator

- (instancetype)initWithOptions:(CreditCardType)options {
	if (self = [super init]) {
		self.options = options;
	}
	return self;
}

- (BOOL)isValid:(NSString *)card {
	if (self.options & CreditCardTypeMASTERCARD) {
		if (card.length == 16 && [GenericValidator matchRegexp:card regexp:@"^5[12345]"]) {
			return YES;
		}
	}
	if (self.options & CreditCardTypeVISA) {
		if (card.length == 16 && [GenericValidator matchRegexp:card regexp:@"^4"]) {
			return YES;
		}
	}
	if (self.options & CreditCardTypeAMEX) {
		if (card.length == 15 && [GenericValidator matchRegexp:card regexp:@"^3[47]"]) {
			return YES;
		}
	}
	if (self.options & CreditCardTypeDINERSCLUB) {
		if (card.length == 14 && [GenericValidator matchRegexp:card regexp:@"^3(?:0[012345]|[68])"]) {
			return YES;
		}
	}
	if (self.options & CreditCardTypeENROUTE) {
		if (card.length == 15 && [GenericValidator matchRegexp:card regexp:@"^2(?:014|149)"]) {
			return YES;
		}
	}
	if (self.options & CreditCardTypeDISCOVER) {
		if (card.length == 16 && [GenericValidator matchRegexp:card regexp:@"^6011"]) {
			return YES;
		}
	}
	if (self.options & CreditCardTypeJCB) {
		if (card.length == 16 && [GenericValidator matchRegexp:card regexp:@"^3"]) {
			return YES;
		}
		if (card.length == 15 && [GenericValidator matchRegexp:card regexp:@"^(?:2131|1800)"]) {
			return YES;
		}
	}
	return NO;
}

@end
