//
//  OPQRCodeViewController.m
//  OneStationPlatform
//
//  Created by SonWa on 15/7/15.
//  Copyright (c) 2015年 SonWa. All rights reserved.
//

#import "OPQRCodeViewController.h"
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>

@interface OPQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate> {
    int num;
    BOOL upOrdown;
    NSTimer * timer;
}

@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;
@property (nonatomic, retain) UIImageView * line;
@property (nonatomic, strong) NSString *bundlePath;

@end

@implementation OPQRCodeViewController

#define ishasNavBar self.navigationController && self.navigationController.navigationBar.hidden == NO
#define scanBoxX (SCREEN_WIDTH - width)*0.5
#define scanBoxY (SCREEN_HEIGHT - height)*0.5
//#define scanBoxY ishasNavBar ? (SCREEN_HEIGHT - height)*0.5-64 : (SCREEN_HEIGHT - height)*0.5

-(NSString *)bundlePath
{
    if (_bundlePath == nil) {
        //获取路径
        NSString * path = [[NSBundle mainBundle] pathForResource:@"RDHomeKit" ofType:@"bundle"];
        _bundlePath = [path stringByAppendingPathComponent:@"images"];
    }
    return _bundlePath;
}

- (BOOL)p_verfilyVideoUseStatus {
    BOOL enable = YES;
    AVAuthorizationStatus status =  [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (status == AVAuthorizationStatusRestricted || status == AVAuthorizationStatusDenied) {
        enable = NO;
        UIAlertController * alertC = [UIAlertController alertControllerWithTitle:@"摄像头访问受限"
                                                                         message:@"请到手机设置里允许APP使用摄像头"
                                                                  preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertC animated:YES completion:nil];
        RDS_WEAKSELF(weakSelf)
        UIAlertAction * action = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
            [weakSelf.navigationController popViewControllerAnimated:YES];
        }];
        [alertC addAction:action];
    }
    return enable;
}

- (void)p_setupCameraWithVerify {
    if ([self p_verfilyVideoUseStatus]) {
        [self setupCamera];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // @"扫一扫";
    self.title = @"";
    self.view.backgroundColor = [UIColor blackColor];
    
    CGFloat width = 0.8*SCREEN_WIDTH;
    CGFloat height = width;
    
    CGFloat x = scanBoxX;
    CGFloat y = scanBoxY+_topOffset;
    
    upOrdown = NO;
    num =0;
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(x, y, width, 2)];
    _line.image = [UIImage imageWithContentsOfFile:[self.bundlePath stringByAppendingPathComponent:@"QRCodeScanLine.png"]];
    [self.view addSubview:_line];
    
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    [self performSelectorOnMainThread:@selector(p_setupCameraWithVerify) withObject:nil waitUntilDone:NO];
    
    // 添加背景view
    CGFloat topSize = scanBoxY+_topOffset;
    CGFloat leftSize = scanBoxX;
    
    UIView *upView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, topSize)];
    upView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view addSubview:upView];
    
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, topSize, leftSize, height)];
    leftView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view addSubview:leftView];
    
    UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-leftSize, topSize, leftSize, height)];
    rightView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view addSubview:rightView];
    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,topSize+height, SCREEN_WIDTH, SCREEN_HEIGHT-(topSize+height))];
    bottomView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view addSubview:bottomView];
    
    UIImageView *leftTopBorder = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:[self.bundlePath stringByAppendingPathComponent:@"ScanQR1.png"]]];
    leftTopBorder.frame = CGRectMake(leftSize, topSize, 16, 16);
    [self.view addSubview:leftTopBorder];
    
    UIImageView *rightTopBorder = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:[self.bundlePath stringByAppendingPathComponent:@"ScanQR2"]]];
    rightTopBorder.frame = CGRectMake(SCREEN_WIDTH-leftSize-16, topSize, 16, 16);
    [self.view addSubview:rightTopBorder];
    
    UIImageView *leftBottomBorder = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:[self.bundlePath stringByAppendingPathComponent:@"ScanQR3"]]];
    leftBottomBorder.frame = CGRectMake(leftSize, topSize+height-16, 16, 16);
    [self.view addSubview:leftBottomBorder];
    
    UIImageView *rightBottomBorder = [[UIImageView alloc]initWithImage:[UIImage imageWithContentsOfFile:[self.bundlePath stringByAppendingPathComponent:@"ScanQR4"]]];
    rightBottomBorder.frame = CGRectMake(SCREEN_WIDTH-leftSize-16, topSize+height-16, 16, 16);
    [self.view addSubview:rightBottomBorder];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, topSize+height+20, SCREEN_WIDTH, 14)];
    [self.view addSubview:label];
    //[label setText:@"将二维码放入框内,即可自动扫描"];
    [label setFont:systemFont(14)];
    [label setTextColor:[UIColor whiteColor]];
    [label setTextAlignment:NSTextAlignmentCenter];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [_session startRunning];
}

-(void)animation1
{
    CGFloat width = 0.8*SCREEN_WIDTH;
    CGFloat height = width;
    
    CGFloat x = scanBoxX;
    CGFloat y = scanBoxY+_topOffset;
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake(x, y+2*num, width, 2);
        if (2*num >= height) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake(x, y+2*num, width, 2);
        if (num == 0) {
            upOrdown = NO;
        }
    }
    
}
-(void)backAction
{
    
//    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self setNeedsStatusBarAppearanceUpdate];
    
    [_session stopRunning];
    
    [self dismissViewControllerAnimated:YES completion:^{
        [self->timer invalidate];
    }];
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_session stopRunning];
    [timer invalidate];
    //[timer setFireDate:[NSDate distantFuture]]; //暂停
}

- (void)setupCamera
{
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    
    CGFloat width = 0.8*SCREEN_WIDTH;
    CGFloat height = width;
    
    CGFloat x = scanBoxX;
    CGFloat y = scanBoxY+_topOffset;
    
    [_output setRectOfInterest:CGRectMake(y/SCREEN_HEIGHT,x/SCREEN_WIDTH,width/SCREEN_HEIGHT,height/SCREEN_WIDTH)];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    _output.metadataObjectTypes =@[AVMetadataObjectTypeQRCode];
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:self.session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =CGRectMake(0, 0, FULL_WIDTH, SCREEN_HEIGHT);
    [self.view.layer insertSublayer:_preview atIndex:0];
    // Start
    [timer setFireDate:[NSDate distantPast]];
    [_session startRunning];
}
#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
    }
    
    
    [_session stopRunning];
    [timer invalidate];
    //[timer setFireDate:[NSDate distantFuture]]; //暂停
    
    if (_delegate && [_delegate respondsToSelector:@selector(rdy_didFinishPickingMediaWithInfo:)]) {
        [_delegate rdy_didFinishPickingMediaWithInfo:stringValue];
    }
    
    [self.navigationController popViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
