//
//  MessageListCell.m
//  EZOpenSDKDemo
//
//  Created by DeJohn Dong on 15/11/3.
//  Copyright © 2015年 Ezviz. All rights reserved.
//

#import "MessageListCell.h"
#import "UIImageView+EzvizOpenSDK.h"
#import "UIImageView+AFNetworking.h"
#import "UIAlertController+DeviceVerifyCodeBySerial.h"

static dispatch_semaphore_t ezviz_sema; //全局信号量

#define device_verify_code_check_queue_name "com.ys7.open.verify.check.queue"

static __unused dispatch_queue_t device_verify_code_check_queue()
{
    static dispatch_queue_t device_verify_check_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        device_verify_check_queue = dispatch_queue_create(device_verify_code_check_queue_name, DISPATCH_QUEUE_SERIAL);
    });
    return device_verify_check_queue;
}

@implementation MessageListCell

- (void)awakeFromNib {
    [super awakeFromNib];
    self.readStatusIcon.layer.cornerRadius = 5.0f;
    self.readStatusIcon.clipsToBounds = YES;
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
    self.readStatusIcon.backgroundColor = [UIColor dd_hexStringToColor:@"0x1b9ee2"];
}

- (void)setAlarmInfo:(EZAlarmInfo *)info {
    self.timeLabel.text = [info.alarmStartTime formattedDateWithFormat:HmsFormat];
    self.readStatusIcon.hidden = info.isRead;
    
    NSURL *url = [NSURL URLWithString:info.alarmPicUrl];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"GET";
    __weak typeof(self) weakSelf = self;
    
    [self.actionImageView ez_setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"message_callhelp"] success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSData * _Nonnull data) {
        BOOL isEncrypt = [self isEncrypt:info.alarmPicUrl];
        
        if (!isEncrypt) {
            weakSelf.actionImageView.image = [[UIImage alloc] initWithData:data];
        } else {
            /*加密url有2种图片链接
             https://whpic.ys7.com:8009/HIK_1447836214_458BEBDAE4AB6a6f_525400286893421023815?isEncrypted=1&isCloudStored=0
             https://www.ys7.com:9090/api/cloud?method=download&fid=5ed92258-8e0f-11e5-8000-c19249a52dcf&deviceSerialNo=504242549&isEncrypted=0&isCloudStored=1
             */
            NSInteger cryptType = info.crypt;
            dispatch_async(device_verify_code_check_queue(), ^{
                // 该demo写的密码方案是简单方案，用户体验一般，用户可以自行实现密码方案，本方案仅供参考
                // 设备加密 & 存有验证码
                if (cryptType == 1 && [GlobalKit shareKit].deviceVerifyCodeBySerial[_deviceSerial] == nil) {
                    if (!ezviz_sema) {
                        ezviz_sema = dispatch_semaphore_create(0);
                    }
                    [weakSelf showSetPassword];
                    dispatch_semaphore_wait(ezviz_sema, DISPATCH_TIME_FOREVER);
                }
                // 获取设备验证码
                NSString *verifyCode = [GlobalKit shareKit].deviceVerifyCodeBySerial[_deviceSerial];
                if (cryptType == 2) {
                    verifyCode = info.checksum;
                }
                
                NSData *decodeData = [EZOPENSDK decryptData:data verifyCode:verifyCode encryptType:cryptType];
                dispatch_async(dispatch_get_main_queue(), ^{
                    weakSelf.actionImageView.image = [[UIImage alloc] initWithData:decodeData];
                    if (weakSelf.actionImageView.image == nil) {
                        weakSelf.actionImageView.image = [UIImage imageNamed:@"message_callhelp"];
                    }
                });
            });
        }
    } failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
        NSLog(@"error = %@",error);
    }];
    self.descriptionLabel.text = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"message_from", @"来自"), info.alarmName];
}

- (void)showSetPassword {
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIAlertController showAlertWithDeviceSerial:_deviceSerial confirmBlock:^(NSString * _Nonnull code) {
            dispatch_semaphore_signal(ezviz_sema);
        } cancelBlock:^{
            dispatch_semaphore_signal(ezviz_sema);
        }];
    });
}

/** 判断图片链接是否是加密 */
- (BOOL)isEncrypt:(NSString *)url {
    int ret = 0;
    NSRange range = [url rangeOfString:@"isEncrypted="];
    if (range.location != NSNotFound) {
        NSString *strIsEncrypted = [url substringWithRange:NSMakeRange(range.location + range.length, 1)];
        if (strIsEncrypted) {
            ret = [strIsEncrypted intValue];
        }
    }
    return ret == 1;
}

@end
