//
//  PairCodeJoinConfController.m
//  HWMSDKDemo
//
//

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

@interface PairCodeJoinConfController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preLayer;
@property (nonatomic, strong) AVCaptureSession * session;

@end

@implementation PairCodeJoinConfController

- (void)viewDidLoad {
    [super viewDidLoad];
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    [self readQRcode];
                } else {
                    [UIUtil showMessage:@"没有摄像头权限"];
                }
            });
        }];
    } else if (authStatus == AVAuthorizationStatusAuthorized) {
        [self readQRcode];
    } else {
        [UIUtil showMessage:@"没有摄像头权限"];
    }
    
}
- (void)readQRcode {

    self.session = [[AVCaptureSession alloc]init];
    //创建一个普通设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //根据普通设备创建一个输入设备
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    //将输入设备关联到会话
    if ([self.session canAddInput:input]) {
        [self.session addInput:input];
    }
    
    //创建一个输出对象
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc]init];
    //输出对象关联到会话
    if ([self.session canAddOutput:output]) {
        [self.session addOutput:output];
    }
    //设置元数据类型，是QR二维码
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    //设置代理，得到解析结果
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];

    
    //创建一个特殊的层
    self.preLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:self.session];
    //设置尺寸并添加到视图树
    self.preLayer.frame = self.view.bounds;
    [self.view.layer addSublayer:self.preLayer];
    
    [self.session startRunning];
}

- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    //停止会话
    [self.session stopRunning];
    //移除显示扫描层
    [self.preLayer removeFromSuperlayer];
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *object = [metadataObjects firstObject];
        NSLog(@"%@",object.stringValue);
        [self joinConf:object.stringValue];
        
    }
}

- (void)joinConf:(NSString *)qrCodeString {
    NSArray<HWMSDKConfListItemModel *> *confList = [[HWMSDKConfMgrService shareInstance] getConfListInfo];
    if (confList.count <= 0) {
        [UIUtil showMessage:@"请先预约一个会议"];
        return;
    }
    HWMSDKConfListItemModel *confInfo = [confList firstObject];
    
    HWMPairCodeJoinConfParam *param = [[HWMPairCodeJoinConfParam alloc] init];
    param.url = qrCodeString;
    param.confId = confInfo.baseInfo.confId;
    param.confPassword = confInfo.baseInfo.hostPwd.length > 0 ? confInfo.baseInfo.hostPwd : confInfo.baseInfo.guestPwd;
    [[HWMSdk getOpenApi] joinPairConf:param callback:^(NSError * _Nullable error, id  _Nullable result) {
        if (error) {
            [UIUtil showMessageWithError:error];
        } else {
            [UIUtil showMessage:[NSString stringWithFormat:@"入会成功，会议ID：%@", confInfo.baseInfo.confId]];
        }
    }];
}

@end
