//
//  Recognition.m
//  Recognition
//
//  Created by Abel on 18/2/23.
//  Copyright (c) 2018年 yf. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <React/RCTLog.h>
#import <React/RCTUtils.h>
#import "Recognition.h"
#import <ZXingObjC/ZXingObjC.h>

@implementation Recognition
RCT_EXPORT_MODULE()

RCT_REMAP_METHOD(decode,
                 path:(NSString *)path
                 resolver:(RCTPromiseResolveBlock)resolve
                 rejecter:(RCTPromiseRejectBlock)reject) {
    UIImage *srcImage;
    if ([path hasPrefix:@"http://"] || [path hasPrefix:@"https://"]) {
        srcImage = [UIImage imageWithData: [NSData dataWithContentsOfURL:[NSURL URLWithString: path]]];
    } else {
        srcImage = [[UIImage alloc] initWithContentsOfFile:path];
    }
    if (nil==srcImage){
        reject(@"-2",@"加载失败",nil);
        return;
    }
    CGImageRef imageToDecode = srcImage.CGImage;  // Given a CGImage in which we are looking for barcodes
    ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
    ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
    NSError *error = nil;
    ZXDecodeHints *hints = [ZXDecodeHints hints];
    ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
    ZXResult *result = [reader decode:bitmap hints:hints error:&error];
    if (result) {
        NSString *contents = result.text;
        resolve(contents);
    } else {
        reject(@"-1",@"未找到二维码或条形码",nil);
    }
}
@end
