#import "../headers/iospermissionutils.h"
#import <AVFoundation/AVFoundation.h>
#import <UIKit/UIKit.h>

IosPermissionUtils::IosPermissionUtils() : QObject(nullptr)
{
    this->_responseWaitLoop = new QEventLoop(this);
}

bool IosPermissionUtils::isCameraPermissionGranted() {
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    return status == AVAuthorizationStatusAuthorized;
}

bool IosPermissionUtils::requestCameraPermission() {
    if(this->isCameraPermissionGranted())
        return true;

    if ([AVCaptureDevice respondsToSelector:@selector(requestAccessForMediaType: completionHandler:)]) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            // Will get here on both iOS 7 & 8 even though camera permissions weren't required
            // until iOS 8. So for iOS 7 permission will always be granted.
            this->_responseWaitLoop->exit(granted);
        }];
    }

    if(!this->_responseWaitLoop->exec()) {
        // permission was not granted -> open settings
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        return false;
    }

    return true;
}
