//
//  ICDbTestViewController.m
//  superCleaner
//
//  Created by Mazy on 2020/7/30.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import <AVFoundation/AVFoundation.h>
#import "ICDbTestViewController.h"
#import "superCleaner-Swift.h"

#define kRecordAudioFile @"myRecord.caf"

@interface ICDbTestViewController ()

@property (weak, nonatomic) IBOutlet UIView *dbContentView;
@property (strong, nonatomic) ICDbDashboardView *paneView;

/** 录音机 */
@property (nonatomic, strong) AVAudioRecorder *audioRecorder;

/** 录音声波监控（注意这里暂时不对播放进行监控） */
@property (nonatomic,strong) NSTimer *timer;

@property(nonatomic, assign) NSInteger minValue;
@property(nonatomic, assign) NSInteger maxValue;

@property (weak, nonatomic) IBOutlet UILabel *minValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *maxValueLabel;

@property (weak, nonatomic) IBOutlet UIView *minValueContentView;
@property (weak, nonatomic) IBOutlet UIView *maxValueContentView;
@property (weak, nonatomic) IBOutlet UIView *tipTextContentView;

@end

@implementation ICDbTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = ICLocalized(@"DecibelDetection");
    self.minValueContentView.layer.cornerRadius = 8;
    self.maxValueContentView.layer.cornerRadius = 8;
    self.tipTextContentView.layer.cornerRadius = 8;
    
    self.paneView = [[ICDbDashboardView alloc] initWithFrame:self.dbContentView.bounds];
    [self.dbContentView addSubview:self.paneView];
//    [self.paneView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.edges.equalTo(self.paneView);
//    }];
    
    self.minValue = 0;
    self.maxValue = 0;
    
    [self setAudioSession];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    if (![self.audioRecorder isRecording]) {
        [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
        self.timer.fireDate=[NSDate distantPast];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [super viewWillDisappear:animated];
    [self.audioRecorder stop];
    self.audioRecorder = nil;
    [self.timer invalidate];
    self.timer = nil;
}

//- (void)viewWillDisAppear:(BOOL)animated {
//    [super viewWillDisappear:animated];
//    [self.audioRecorder stop];
//    self.audioRecorder = nil;
//    [self.timer invalidate];
//    self.timer = nil;
//}

#pragma mark - 录音方法
/**
 *  设置音频会话
 */
-(void)setAudioSession{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //设置为录音状态，
    [audioSession setCategory: AVAudioSessionCategoryRecord error:nil];
    [audioSession setActive:YES error:nil];
}

/**
 *  取得录音文件保存路径
 *
 *  @return 录音文件路径
 */
-(NSURL *)getSavePath{
    NSString *urlStr=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    urlStr=[urlStr stringByAppendingPathComponent:kRecordAudioFile];
    NSLog(@"file path:%@",urlStr);
    NSURL *url=[NSURL fileURLWithPath:urlStr];
    return url;
}

/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
- (NSDictionary *)getAudioSetting {
    
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    // 设置录音格式为lpcm
    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    // 设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    // 声道
    [dicM setObject:@(2) forKey:AVNumberOfChannelsKey];
    // 每个采样点位数
    [dicM setObject:@(8) forKey:AVLinearPCMBitDepthKey];
    // 是否使用浮点数采样
    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    // 录音品质
    [dicM setObject:@(AVAudioQualityHigh) forKey:AVSampleRateConverterAudioQualityKey];
    return dicM;
}

- (AVAudioRecorder *)audioRecorder {
    if (!_audioRecorder) {
        // 保存路径
        NSURL *url = [self getSavePath];
        // 录音设置
        NSDictionary *setting = [self getAudioSetting];
        // 创建录音机
        NSError *error = nil;
        _audioRecorder = [[AVAudioRecorder alloc] initWithURL:url settings:setting error:&error];
//        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled = YES;
        
        if (error) {
            NSLog(@"创建录音机对象发生错误，error：%@", error.localizedDescription);
            return nil;
        }
        
    }
    return _audioRecorder;
}

/**
 *  录音声波监控定制器
 *
 *  @return 定时器
 */
-(NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval: 0.5f target:self selector:@selector(audioPowerChange) userInfo:nil repeats:YES];
    }
    return _timer;
}

/**
 *  录音声波状态设置
 */
-(void)audioPowerChange{
    
    [self.audioRecorder updateMeters];//更新测量值
    float power = [self.audioRecorder averagePowerForChannel:0];
//    float powerMax = [self.audioRecorder peakPowerForChannel:0];
//    NSLog(@"power = %f, powerMax = %f",power, powerMax);
    
//    CGFloat progress = (1.0 / 160.0) * (power + 160.0);
    
    power = power + 150  - 50;
    
    int dB = 0;
    if (power < 0.f) {
        dB = 0;
    } else if (power < 40.f) {
        dB = (int)(power * 0.875);
    } else if (power < 100.f) {
        dB = (int)(power - 15);
    } else if (power < 110.f) {
        dB = (int)(power * 2.5 - 165);
    } else {
        dB = 110;
    }
    self.paneView.dbValue = dB;
    self.paneView.progressValue = (CGFloat)dB / 110.0;
    
    if (self.minValue == 0 || self.maxValue == 0) {
        self.minValue = dB;
        self.maxValue = dB;
    }
    
    if (self.minValue > dB) {
        self.minValue = dB;
    }
    
    if (self.maxValue < dB) {
        self.maxValue = dB;
    }
    
    self.minValueLabel.text = [NSString stringWithFormat:@"%lddB", self.minValue];
    self.maxValueLabel.text = [NSString stringWithFormat:@"%lddB", self.maxValue];
    
//    self.paneView.todoTask = dB;
    NSLog(@"progress, dB = %f", (CGFloat)dB / 110.0);
//    self.powerLabel.text = [NSString stringWithFormat:@"%ddB", dB];
//    [self.audioPower setProgress:progress];

}

- (void)dealloc
{
    NSLog(@"ICDbTestViewController dealloc");
}

@end
