//
//  ICCleanDustViewController.m
//  superCleaner
//
//  Created by Mazy on 2020/7/29.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICCleanDustViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "UIImageView+Rotate.h"
#import "QiSlider.h"
#import <MediaPlayer/MediaPlayer.h>

typedef enum : NSUInteger {
    ClearDustType,
    DriveMosType,
    DrivePetType,
} ICPlayVoiceType;

@interface ICCleanDustViewController ()<AVAudioPlayerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *startButton;

@property (weak, nonatomic) IBOutlet UIView *imageContentView;

@property (weak, nonatomic) IBOutlet UIView *subContentView;

@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *topActionButtons;

@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *actionTipLabels;

@property (weak, nonatomic) IBOutlet UIImageView *bgCycleImageView;

@property (weak, nonatomic) IBOutlet UIView *sliderContentView;

@property (weak, nonatomic) IBOutlet UIImageView *centerImageView;

@property (nonatomic, assign) ICPlayVoiceType voiceType;

@property (nonatomic, assign) BOOL stopAnimation;

@property (nonatomic, strong) QiSlider *slider;

@property (nonatomic, strong) AVAudioPlayer *player;

@property(nonatomic, assign) float currentVolume;

@end

@implementation ICCleanDustViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = ICLocalized(@"PhoneCleaning");
    
    self.stopAnimation = true;
    
    self.voiceType = ClearDustType;
    
    self.imageContentView.layer.cornerRadius = 53;
    self.subContentView.layer.cornerRadius = 75;
    
    QiSlider *slider = [[QiSlider alloc] init];
    slider.minimumValue = 1;
    slider.maximumValue = 60;
    slider.thumbTintColor =  kMassColor;
    slider.minimumTrackTintColor = kMassColor;
    slider.maximumTrackTintColor = [UIColor colorWithHex:0xE5E5E5];

    slider.valueFont = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    slider.valueTextColor = [UIColor colorWithHex:0x22293D];
    [self.sliderContentView addSubview: slider];
    [slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.sliderContentView);
    }];
    slider.valueChanged = ^(QiSlider *slider) {
        NSLog(@"%f", slider.value);
        if (self.player) {
            switch (self.voiceType) {
                case ClearDustType:
                    self.player.numberOfLoops = (NSInteger)(slider.value);
                    break;
                case DriveMosType:
                    self.player.numberOfLoops = (NSInteger)(slider.value  * 2);
                    break;
                case DrivePetType:
                    self.player.numberOfLoops = (NSInteger)(slider.value  * 15);
                    break;
                default:
                    break;
            }
        }
    };
    self.slider = slider;
    [self.slider setValue:2 animated:true];
    [self.slider setValue:1 animated:true];
    
    //"Start" = "Start";
//    "Pause" = "Pause";
    [self.startButton setTitle: ICLocalized(@"Start") forState:UIControlStateNormal];
    [self.startButton setTitle: ICLocalized(@"Pause") forState:UIControlStateSelected];
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:true error:nil];
    
    //and whereever you want to play the sound, call the lines below
    float currentVolume = [MPMusicPlayerController applicationMusicPlayer].volume; //grab current User volume
    self.currentVolume = currentVolume;
    [[MPMusicPlayerController applicationMusicPlayer] setVolume:1.0];//set system vol to max
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.player stop];
    self.player = nil;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:false error:nil];
    
    //and the setVolumeBackToNormal function calls this line below
    [[MPMusicPlayerController applicationMusicPlayer] setVolume: self.currentVolume];//returns volume to original setting
}

- (IBAction)topActionButtonAction:(UIButton *)sender {
    sender.selected = !sender.isSelected;
        
    [self.startButton setSelected:false];
    
    [self.bgCycleImageView pauseAnimations];
    
    if (self.player) {
        [self.player stop];
        self.player = nil;
    }
    for (UIButton *button in self.topActionButtons) {
        if (button.tag != sender.tag) {
            button.selected = false;
        }
    }
    
    for (UILabel *label in self.actionTipLabels) {
        if (label.tag - 1000 == sender.tag) {
            label.textColor = kMassColor;
        } else {
            label.textColor = [UIColor colorWithHex:0x1B3644];
        }
    }
    
    switch (sender.tag) {
        case 1000:
            self.centerImageView.image = [UIImage imageNamed: @"tool_dust_image"];
            self.voiceType = ClearDustType;
            self.bgCycleImageView.image = [UIImage imageNamed:@"tool_dust_clean_cycle_icon_1"];
            break;
        case 1001:
            self.centerImageView.image = [UIImage imageNamed: @"tool_mos_image"];
            self.voiceType = DriveMosType;
            self.bgCycleImageView.image = [UIImage imageNamed:@"tool_dust_clean_cycle_icon"];
            break;
        case 1002:
            self.centerImageView.image = [UIImage imageNamed: @"tool_pet_icon"];
            self.voiceType = DrivePetType;
            self.bgCycleImageView.image = [UIImage imageNamed:@"tool_dust_clean_cycle_icon"];
            break;
        default:
            break;
    }
    
    self.stopAnimation = true;
}

- (IBAction)startPlayAction:(UIButton *)sender {
    
    sender.selected = !sender.isSelected;
        
    NSString *mp3Name = @"dust.mp3";
    switch (self.voiceType) {
        case ClearDustType:
            mp3Name = @"dust.mp3";
            break;
        case DriveMosType:
            mp3Name = @"flys.mp3";
            break;
        case DrivePetType:
            mp3Name = @"pets.mp3";
            break;
        default:
            break;
    }
    
    if (self.player) {
        if (sender.isSelected) {
            [self.player play];
            [self.bgCycleImageView resumeAnimations];
        } else {
            [self.player pause];
            [self.bgCycleImageView pauseAnimations];
        }
    } else {
        //播放本地音乐
        NSURL *fileURL = [[NSBundle mainBundle] URLForResource:mp3Name withExtension:@""];
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
        self.player.delegate = self;
        [self.player setVolume:1110.0];
        [self.player prepareToPlay];
        [self.player play];
        
        [self.bgCycleImageView rotate360WithDuration:1 repeatCount:0];
        [self.bgCycleImageView resumeAnimations];
    }
}


// 音频播放器播放的音频结束后会
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
    NSLog(@"播放结束");
    [self.player stop];
     [self.bgCycleImageView pauseAnimations];
}

// 解码错误的时候会调用这个方法
- (void)audioPlayerDecodeErrorDidOccur:(AVAudioPlayer *)player error:(NSError *)error {
    NSLog(@"文件出错");
    [self.player stop];
     [self.bgCycleImageView pauseAnimations];
}

@end
