//
//  CarSecurityViewController.m
//  goodpk
//
//  Created by 歐特儀 on 2020/2/11.
//  Copyright © 2020 Altob. All rights reserved.
//

#import "CarSecurityViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import "CarSecurityModdel.h"
#import "LockCarViewController.h"
#import "CocoaSecurity.h"
#import "Util.h"

#define APIURL @"https://cloudservice.altob.com.tw/LockCarSerivce/api/JumpApi"
#define CARSECURITY @"/CARSECURITY?"
#define ALPHANUM @"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"

@interface CarSecurityViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *AcctInput;
@property (weak, nonatomic) IBOutlet UITextField *PwdInput;
@property (weak, nonatomic) IBOutlet UIButton *okBtn;

@end

@implementation CarSecurityViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"會員防竊車";
    
    [self.okBtn addTarget:self
            action:@selector(okButtonClicked:)
            forControlEvents:UIControlEventTouchUpInside
    ];
    
    //注册截圖通知
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(userDidTakeScreenshot:)
                                                 name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    self.AcctInput.delegate = self;
    self.PwdInput.delegate = self;
    self.AcctInput.keyboardType = UIKeyboardTypeASCIICapable;
    self.PwdInput.keyboardType = UIKeyboardTypeASCIICapable;
    
}

- (BOOL)textField:(UITextField* )textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString* )string
{
    if (textField == self.AcctInput)
    {
       NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
       NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if([string isEqualToString:filtered]){
            NSUInteger newLength = [textField.text length] + [string length] - range.length;
            return (newLength > 10 ) ? NO : YES;
        }else{
            return NO;
        }
    }else if(textField == self.PwdInput){
        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:ALPHANUM] invertedSet];
        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];
        if([string isEqualToString:filtered]){
            NSUInteger newLength = [textField.text length] + [string length] - range.length;
            return (newLength > 20 ) ? NO : YES;
        }else{
            return NO;
        }
    }
    else
    {
      return true;
    }

}

- (void) okButtonClicked:(id)sender {
    if([self.AcctInput.text length] == 0){
        [self showAlert:@"錯誤" :@"請輸入帳號" :nil];
    }else if([self.PwdInput.text length] == 0){
        [self showAlert:@"錯誤" :@"請輸入密碼" :nil];
    }else{
        //打API
        [self Login:self.AcctInput.text :self.PwdInput.text];
    }
}

-(void)showAlert:(NSString *)title :(NSString *)text: (NSInteger *)type{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title
                                        message:text
                                        preferredStyle:UIAlertControllerStyleAlert ];
    
    UIAlertAction *sinupAction = [UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
       
    }];
    [alertController addAction:sinupAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void) Login:(NSString *)acct :(NSString *)pwd {
    
    CocoaSecurityResult *Nacct = [CocoaSecurity aesEncrypt:acct key:[Util sha256HashFor:@"Altob"]];
    
    NSString *mPwd = [self md5:pwd];
    NSString *status = @"2";
    //NSLog(@"加密字串：%@", [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", mPwd, @"iii", status]);
    NSString *key = [self md5: [NSString stringWithFormat:@"%@%@%@%@%@", acct, @"i", mPwd, @"iii", status]];
    NSString *carUrl = [NSString stringWithFormat:@"%@%@acct=%@&pwd=%@&status=%@&key=%@&station=%@", APIURL, CARSECURITY, Nacct.base64, mPwd, status, key, self.station];
    
    //第一步，创建URL
    NSURL *url = [NSURL URLWithString:carUrl];
    //NSDictionary *jsonBodyDict = @{};
    
    //NSLog(@"URL: %@", url);
    
    //第二步，创建请求
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //设置请求方式为POST，默认为GET
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"Bearer 9a406a82bd551e6ef8e845f42f788af4" forHTTPHeaderField:@"Authorization"];
    [request setHTTPMethod:@"GET"];
    
    //设置参数
    //NSData *jsonBodyData = [NSJSONSerialization dataWithJSONObject:jsonBodyDict options:kNilOptions error:nil];
    //[request setHTTPBody:jsonBodyData];
    
    //新作法
    NSURLSession *sesson = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];
    
    // 2.创建 NSURLSessionDataTask
    NSURLSessionDataTask *dataTask = [sesson dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
         if (error) {
             NSLog(@"%@", error);
             // error
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self showAlert: @"注意" : @"您所使用的連線加密(SSL)異常，基於安全考量不提供相關功能。請確認您的連線環境及App下載來源安全。" : 0];
             });
         }else {
             // 获得数据后，返回到主线程更新 UI
             dispatch_async(dispatch_get_main_queue(), ^{
                 NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                 CarSecurityModdel *CS = [[CarSecurityModdel alloc] initWithString:responseString error:nil];
                 if([CS.result_code isEqual:@"OK"]){
                     //鎖車頁面
                     UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"LockCar" bundle:[NSBundle mainBundle]];
                     LockCarViewController *HelpController = [storyboard instantiateViewControllerWithIdentifier:@"LockCar"];
                     HelpController.status = CS.result_msg;
                     HelpController.acct = acct;
                     HelpController.pwd = mPwd;
                     HelpController.station = self.station;
                     [self.navigationController pushViewController:HelpController animated:YES];
                 }else{
                     [self showAlert:@"錯誤" :@"登入失敗，請稍後再試" :nil];
                 }
             });
         }
    }];
    // 3.执行 Task
    [dataTask resume];
    
    /*
    //第三步，连接服务器
    NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    NSString *jsonString = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
    //NSLog(@"CAR LOGIN:%@", jsonString);
    
    CarSecurityModdel *CS = [[CarSecurityModdel alloc] initWithString:jsonString error:nil];
    if([CS.result_code isEqual:@"OK"]){
        //鎖車頁面
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"LockCar" bundle:[NSBundle mainBundle]];
        LockCarViewController *HelpController = [storyboard instantiateViewControllerWithIdentifier:@"LockCar"];
        HelpController.status = CS.result_msg;
        HelpController.acct = acct;
        HelpController.pwd = mPwd;
        [self.navigationController pushViewController:HelpController animated:YES];
    }else{
        [self showAlert:@"錯誤" :@"登入失敗，請稍後再試" :nil];
    }
    */
}

- (NSString *) md5:(NSString *) input
{
 const char *cStr = [input UTF8String];
 unsigned char digest[16];
 CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call

 NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];

 for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
 [output appendFormat:@"%02x", digest[i]];

 return  output;

}

//截屏响应
- (void)userDidTakeScreenshot:(NSNotification *)notification
{
    [self showAlert: @"注意" : @"偵測到截圖,請妥善保管截圖,避免重要資訊外流" : 0];
}

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler//通过调用block，来告诉NSURLSession要不要收到这个证书
{
   // Get remote certificate
   SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
   SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
    
   // Set SSL policies for domain name check
   NSMutableArray *policies = [NSMutableArray array];
   [policies addObject:(__bridge_transfer id)SecPolicyCreateSSL(true, (__bridge CFStringRef)challenge.protectionSpace.host)];
   SecTrustSetPolicies(serverTrust, (__bridge CFArrayRef)policies);

   // Evaluate server certificate
   SecTrustResultType result;
   SecTrustEvaluate(serverTrust, &result);
    
   BOOL certificateIsValid = (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed);
    
   // Get local and remote cert data
   NSData *remoteCertificateData = CFBridgingRelease(SecCertificateCopyData(certificate));
    
    NSString *hash = [[self doSha256:remoteCertificateData] base64EncodedStringWithOptions:0];
    
   // The pinnning check
   if ([hash isEqualToString:@"FHloZIw4i6+30lmxrUujLieHlIDpxHySL1niMxvgmpU="] && certificateIsValid) {
       NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust];
       completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
   } else {
       completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, NULL);
   }
}

- (NSData *)doSha256:(NSData *)dataIn {
    NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
    CC_SHA256(dataIn.bytes, dataIn.length, macOut.mutableBytes);
    return macOut;
}

@end
