//
//  JKLockController.m
//  Lock
//
//  Created by Jack on 2016/10/13.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "JKLockController.h"
#import "JKLockButton.h"
#import "JKDotView.h"
#import "JKMessageBoxController.h"
#import "AppDelegate.h"

#define Password_Length 4
#define Dot_Interval 60
#define Dot_Width 20

#define View_Tag 10086

@interface JKLockController ()

@property (nonatomic,strong) UILabel *tipLabel;///<提示标签
@property (nonatomic,copy) NSString *password;///<密码
@property (nonatomic,strong) UIButton *forgottenButton;
@property (nonatomic,strong) UIButton *resetButton;
@property (nonatomic,strong) NSMutableArray *dotArray;///<密码视图
@property (nonatomic,copy) NSString *input;///<输入
@property (nonatomic,assign) NSUInteger index;///<输入了多少位

@property (nonatomic,copy,readonly) NSString *passwordKey;///<取密码的钥匙

@end

@implementation JKLockController

- (void)setPasswordKey:(NSString *)passwordKey {
    _passwordKey = passwordKey;
}

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:0.8];
        
        self.dotStrokColor = [UIColor colorWithRed:0.4737 green:0.3641 blue:0.2456 alpha:0.5];
        self.dotFillColor = [UIColor colorWithRed:0.4737 green:0.3641 blue:0.2456 alpha:0.5];
        
        self.lockStrokColor = [UIColor colorWithRed:0.4737 green:0.3641 blue:0.2456 alpha:0.5];
        self.lockHighlightColor = [UIColor colorWithRed:0.4737 green:0.3641 blue:0.2456 alpha:0.5];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = self.backgroundColor;
        
    self.index = 0;
    self.input = @"";
    [self loadPassword];
    [self configAppearance];
    
}

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

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    
    [self configAppearance];
}

- (void)clearView {
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
        [self.dotArray removeAllObjects];
    }
}

- (void)configAppearance {
    CGFloat width = CGRectGetWidth(self.view.bounds);
    CGFloat height = CGRectGetHeight(self.view.bounds);
    
//    [self clearView];
    
    // 20
    CGFloat y0 = height * 0.2;
    self.tipLabel.center = CGPointMake(width / 2, y0 + CGRectGetHeight(self.tipLabel.bounds) / 2);
    [self.view addSubview:self.tipLabel];
    
    // 10
    CGFloat y1 = y0 + CGRectGetHeight(self.tipLabel.bounds) + 20; // 间距20，高度20
    CGFloat x1 = (width - Dot_Width * Password_Length - Dot_Interval * (Password_Length - 1)) / 2;
    for (int i = 0; i < Password_Length; i++) {
        JKDotView *dotView = [self.view viewWithTag:View_Tag + 20 + i];
        if (dotView) {
            dotView.frame = CGRectMake(x1 + (Dot_Width + Dot_Interval) * i, y1, Dot_Width, Dot_Width);
        } else {
            JKDotView *dot = [[JKDotView alloc] initWithFrame:CGRectMake(x1 + (Dot_Width + Dot_Interval) * i, y1, Dot_Width, Dot_Width) strokColor:self.dotStrokColor fillColor:self.dotFillColor];
            dot.tag = View_Tag + 20 + i;
            
            [self.view addSubview:dot];
            [self.dotArray addObject:dot];
        }
    }
    
    // 70
    // 3 * 4
    CGFloat y2 = y1 + Dot_Width + 0.1 * height; // 间距 80 / 40
    CGFloat Button_Width = 0.07 * (width > height ? height : width);
    CGFloat interval = 0.05 * (width > height ? height : width);
    CGFloat x2 = (width - Button_Width * 3 - interval * 2) / 2;
    
    for (int i = 0; i < 3; i++) { // col
        
        for (int j = 0; j < 4; j++) { // row
            
            int index = 3 * j + i + View_Tag + 50;
            UIView *view = [self.view viewWithTag:index];
            
            if (i == 0 && j == 3) { // 取消
                
                if (!view) {
                    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    cancelBtn.frame = CGRectMake(x2 + (Button_Width + interval) * i, y2 + (Button_Width + interval) * j, Button_Width, Button_Width);
                    [cancelBtn setTitle:@"cancel" forState:UIControlStateNormal];
                    [cancelBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [cancelBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
                    [cancelBtn addTarget:self action:@selector(cancelButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                    [self.view addSubview:cancelBtn];
                    cancelBtn.tag = index;
                } else {
                    view.frame = CGRectMake(x2 + (Button_Width + interval) * i, y2 + (Button_Width + interval) * j, Button_Width, Button_Width);
                }
                
            } else if (i == 2 && j == 3) { // 删除
                
                if (view) {
                    view.frame = CGRectMake(x2 + (Button_Width + interval) * i, y2 + (Button_Width + interval) * j, Button_Width, Button_Width);
                } else {
                    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                    deleteBtn.frame = CGRectMake(x2 + (Button_Width + interval) * i, y2 + (Button_Width + interval) * j, Button_Width, Button_Width);
                    [deleteBtn setTitle:@"delete" forState:UIControlStateNormal];
                    [deleteBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    [deleteBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
                    [deleteBtn addTarget:self action:@selector(deleteButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                    [self.view addSubview:deleteBtn];
                    deleteBtn.tag = index;
                }
                
            } else { // 数字
                JKLockButton *btn = (JKLockButton *)view;
                if (btn) {
                    btn.frame = CGRectMake(x2 + (Button_Width + interval) * i, y2 + (Button_Width + interval) * j, Button_Width, Button_Width);
                } else {
                    btn = [[JKLockButton alloc] initWithFrame:CGRectMake(x2 + (Button_Width + interval) * i, y2 + (Button_Width + interval) * j, Button_Width, Button_Width) strokColor:self.lockStrokColor highlightColor:self.lockHighlightColor];
                    if (i == 1 && j == 3) {
                        btn.number = 0;
                    } else {
                        btn.number = 1 + i + j * 3;
                    }
                    [self.view addSubview:btn];
                    [btn addTarget:self action:@selector(numberButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                    btn.tag = index;
                }

                
            }
            
        }
        
    }
    
    // forget
    self.forgottenButton.frame = CGRectMake(width - 120, height - 40, 120, 40);
    [self.view addSubview:self.forgottenButton];
    
    // reset
    self.resetButton.frame = CGRectMake(0, height - 40, 120, 40);
    [self.view addSubview:self.resetButton];
    
}

- (void)loadPassword {
    
    NSString *password = [[NSUserDefaults standardUserDefaults] objectForKey:self.passwordKey];
    self.password = password;
    
}

- (void)setPassword:(NSString *)password {
    _password = password;
    if (password) {
        self.tipLabel.text = @"Please Input Your Password";
    } else {
        self.tipLabel.text = @"Please Set A Password";
    }
}

- (UILabel *)tipLabel {
    if (!_tipLabel) {
        _tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 20)];
        _tipLabel.font = [UIFont systemFontOfSize:20.0f];
        _tipLabel.textAlignment = NSTextAlignmentCenter;
        
    }
    return _tipLabel;
}

- (UIButton *)forgottenButton {
    if (!_forgottenButton) {
        _forgottenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_forgottenButton setTitle:@"forget password" forState:UIControlStateNormal];
        [_forgottenButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        _forgottenButton.tag = View_Tag + 2;
        _forgottenButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [_forgottenButton addTarget:self action:@selector(forgottenButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _forgottenButton;
}

- (UIButton *)resetButton {
    if (!_resetButton) {
        _resetButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_resetButton setTitle:@"reset password" forState:UIControlStateNormal];
        [_resetButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
        _resetButton.tag = View_Tag + 2;
        _resetButton.titleLabel.font = [UIFont systemFontOfSize:14.0f];
        [_resetButton addTarget:self action:@selector(resetButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _resetButton;
}

- (NSMutableArray *)dotArray {
    if (!_dotArray) {
        _dotArray = [NSMutableArray arrayWithCapacity:Password_Length];
    }
    return _dotArray;
}

- (void)numberButtonClick:(JKLockButton *)sender {
    if (self.index < Password_Length) {
        NSInteger number = sender.number;
        JKDotView *dot = [self.dotArray objectAtIndex:self.index];
        dot.state = JKDotStateSelected;
        
        self.input = [self.input stringByAppendingString:[NSString stringWithFormat:@"%d",number]];
        self.index++;
    }
    
    if (self.index == Password_Length) {
        
        [self performSelector:@selector(verifyPassword) withObject:nil afterDelay:0.5];
    }
}

- (void)cancelButtonClick:(UIButton *)sender {
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)deleteButtonClick:(UIButton *)sender {
    if (self.index > 0) {
        
        JKDotView *dot = [self.dotArray objectAtIndex:self.index - 1];
        dot.state = JKDotStateNormal;
        
        self.input = [self.input substringToIndex:self.index - 1];
        self.index--;
        
    }
}

- (void)forgottenButtonClick:(UIButton *)sender {

    JKMessageBoxController *messageBoxController = [JKMessageBoxController messageBoxControllerWithTip:@"Please enter your login password"];
    
    __weak typeof(messageBoxController) weakVC = messageBoxController;
    __weak typeof(self) weakself = self;
    
    messageBoxController.changeHandler = ^(UITextField *textField,NSRange range,NSString *string) {
        
        return YES;
    };
    
    messageBoxController.textHandler = ^(NSString *text){
        
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        
        if ([text isEqualToString:appDelegate.password]) {
            
//            [[NSUserDefaults standardUserDefaults] removeObjectForKey:self.passwordKey];
//            weakself.password = nil;
            weakself.index = 0;
            weakself.input = @"";
            for (JKDotView *dot in self.dotArray) {
                dot.state = JKDotStateNormal;
            }
            
//            weakself.tipLabel.text = @"Please Set A New Password";
            [weakVC dismissViewControllerAnimated:YES completion:^{
//                weakself.tipLabel.text = @"Please Set A New Password";
                
                    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Your Current Password" message:weakself.password preferredStyle:UIAlertControllerStyleAlert];

                
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
                        if (alertController.navigationController) {
                            [alertController.navigationController popViewControllerAnimated:YES];
                        } else {
                            [alertController dismissViewControllerAnimated:YES completion:nil];
                        }
                
                    }];
                
                    [alertController addAction:action];
                    

                    [weakself presentViewController:alertController animated:YES completion:nil];


                
            }];
            
        } else {
            
            [weakVC warning:@"It's wrong,please try again"];
            
        }
        
        
        
        
    };
    
    [self presentViewController:messageBoxController animated:YES completion:nil];
    
}

- (void)resetButtonClick:(UIButton *)sender {
    JKMessageBoxController *messageBoxController = [JKMessageBoxController messageBoxControllerWithTip:@"Please enter your login password"];
    
    __weak typeof(messageBoxController) weakVC = messageBoxController;
    __weak typeof(self) weakself = self;
    
    messageBoxController.changeHandler = ^(UITextField *textField,NSRange range,NSString *string) {
        
        return YES;
    };
    
    messageBoxController.textHandler = ^(NSString *text){
        
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        
        if ([text isEqualToString:appDelegate.password]) {
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:self.passwordKey];
            weakself.password = nil;
            weakself.index = 0;
            weakself.input = @"";
            for (JKDotView *dot in self.dotArray) {
                dot.state = JKDotStateNormal;
            }
            
            weakself.tipLabel.text = @"Please Set A New Password";
            [weakVC dismissViewControllerAnimated:YES completion:^{
                weakself.tipLabel.text = @"Please Set A New Password";
                
            }];
            
        } else {
            
            [weakVC warning:@"It's wrong,please try again"];
            
        }
        
        
        
        
    };
    
    [self presentViewController:messageBoxController animated:YES completion:nil];
}


- (void)verifyPassword {
    
    self.index = 0;
    for (JKDotView *dot in self.dotArray) {
        dot.state = JKDotStateNormal;
    }
    
    if (self.password) { // 验证
        DebugLog(@"password: %@",self.password);
        if ([self.password isEqualToString:self.input]) {
            
            [[NSUserDefaults standardUserDefaults] setObject:self.password forKey:self.passwordKey];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            self.tipLabel.text = @"Please Input Your Password";
            [self cancelButtonClick:nil];// 返回前一个页面
            sleep(0.25);// 先回到前一个页面才做事情，0.25s为隐式动画持续时间
            if (self.authoReturn) {
                self.authoReturn(YES);
            }
            
            
        } else {
            
            self.tipLabel.text = @"The Password Doesn't Match,Please Try Again";
        }
        
    } else { //设置
        
        self.password = self.input;
        self.tipLabel.text = @"Please re-enter password to confirm";
    }
    self.input = @"";
}


@end
