//
// PrivacyUtils.m
// GotoBus
//
// Created by haibara on 1/15/15.
//
//

#import "PrivacyUtils.h"
#import <AVFoundation/AVFoundation.h>

@implementation PrivacyUtils

#pragma mark - Public

+ (BOOL)authorizeCamera {
	return [self authorizeDeviceForMediaType:AVMediaTypeVideo];
}

+ (BOOL)authorizeCalendarForEventsWithStore:(EKEventStore *)store {
	return [self authorizeEventStore:store forEntityType:EKEntityTypeEvent];
}

#pragma mark - Private

+ (BOOL)authorizeDeviceForMediaType:(NSString *)mediaType {
	__block BOOL flag = NO;
	AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
	if (status == AVAuthorizationStatusNotDetermined) {
		dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
		[AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
			if (granted) {
				flag = YES;
			}
			dispatch_semaphore_signal(semaphore);
		}];
		dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
	} else if (status == AVAuthorizationStatusAuthorized) {
		flag = YES;
	}
	return flag;
}

+ (BOOL)authorizeEventStore:(EKEventStore *)store forEntityType:(EKEntityType)entityType {
	__block BOOL flag = NO;
	EKAuthorizationStatus status = [EKEventStore authorizationStatusForEntityType:entityType];
	if (status == EKAuthorizationStatusNotDetermined) {
		dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
		[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
			if (granted) {
				flag = YES;
			}
			dispatch_semaphore_signal(semaphore);
		}];
		dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
	} else if (status == EKAuthorizationStatusAuthorized) {
		flag = YES;
	}
	return flag;
}

@end
