//
//  ExportCertViewController.m
//  EugineAPISample
//
//  Created by aaab on 2023/01/26.
//

#import "ExportCertViewController.h"
#import "ComboBox.h"
#import "SmartChampAPI.h"
#import "UITextField+Addition.h"
#import "ComUtil.h"

@interface ExportCertViewController () <IComboBox>
{
    ComboBox *box;
    NSString *certDN;
    UITextField *certPwdTextField;
    
    UITextField *firstNumber;
    UITextField *secondNumber;
    UITextField *thirdNumber;
    
    UIButton    *exportButton;
}
@end

@implementation ExportCertViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    // Do any additional setup after loading the view.
    
    [self makeCloseButton];
}

- (void)makeCloseButton
{
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(CGRectGetWidth(self.view.frame) - 50 , 15, 35, 35)];
    [button addTarget:self action:@selector(onCloseButton:) forControlEvents:UIControlEventTouchUpInside];
    UIImage *image = [UIImage imageNamed:@"ic_floating_close_48.png"];
    [button setImage:image forState:UIControlStateNormal];
    [button setImage:image forState:UIControlStateHighlighted];
    [self.view addSubview:button];
    
    
    CGFloat padding = 20;
    CGFloat controlWidth = CGRectGetWidth(self.view.frame) - padding * 2;
    ComboBox *box = [[ComboBox alloc] initWithFrame:CGRectMake(padding, 50 + padding, controlWidth, 40)];
    [box setComboDelegate:self];
    [box setPlaceHolder:@"공동인증서 선택"];
    [box setKeys:[self getCertDNList] title:[self getCertUserList]];
    [self.view addSubview:box];
    certDN = [box getSelectkey];
    
    
    certPwdTextField = [[UITextField alloc] initWithFrame:CGRectMake(padding, CGRectGetMaxY(box.frame) + padding, CGRectGetWidth(box.frame), CGRectGetHeight(box.frame))];
    [certPwdTextField setPlaceholder:@"  공동인증 비밀번호"];
    [certPwdTextField setBorderStyle:UITextBorderStyleRoundedRect];
//    [certPwdTextField setDelegate:self];
    [certPwdTextField setTag:2];
    [certPwdTextField setSecureTextEntry:YES];
    [certPwdTextField addNumericAccessory:NO];
    [self.view addSubview:certPwdTextField];
    
    CGFloat numberWidth = (controlWidth - 20) / 3;
    firstNumber = [[UITextField alloc] initWithFrame:CGRectMake(padding, CGRectGetMaxY(certPwdTextField.frame) + padding, numberWidth, CGRectGetHeight(box.frame))];
    [firstNumber setKeyboardType:UIKeyboardTypeNumberPad];
    [firstNumber addNumericAccessory:NO];
    [ComUtil makeRoundView:firstNumber radius:4 width:1 bordercolor:[UIColor lightGrayColor]];
    [self.view addSubview:firstNumber];
    
    secondNumber = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(firstNumber.frame) + 10, CGRectGetMinY(firstNumber.frame), numberWidth, CGRectGetHeight(box.frame))];
    [secondNumber setKeyboardType:UIKeyboardTypeNumberPad];
    [secondNumber addNumericAccessory:NO];
    [ComUtil makeRoundView:secondNumber radius:4 width:1 bordercolor:[UIColor lightGrayColor]];
    [self.view addSubview:secondNumber];
    
    thirdNumber = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(secondNumber.frame) + 10, CGRectGetMinY(firstNumber.frame), numberWidth, CGRectGetHeight(box.frame))];
    [thirdNumber setKeyboardType:UIKeyboardTypeNumberPad];
    [thirdNumber addNumericAccessory:NO];
    [ComUtil makeRoundView:thirdNumber radius:4 width:1 bordercolor:[UIColor lightGrayColor]];
    [self.view addSubview:thirdNumber];
    
    
    exportButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [exportButton setFrame:CGRectMake(padding, CGRectGetMaxY(thirdNumber.frame) + 20 , controlWidth, CGRectGetHeight(box.frame))];
    [exportButton setTitle:@"내보내기" forState:UIControlStateNormal];
    [exportButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [exportButton addTarget:self action:@selector(onExportButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:exportButton];
    [ComUtil makeRoundView:exportButton radius:4 width:1 bordercolor:[UIColor blackColor]];
    
}


- (NSArray*)getCertDNList{
    NSArray *array = [[SmartChampAPI instance] getUserCertList];
    
    NSMutableArray *arrayCert = [NSMutableArray array];
    for ( NSInteger i = 0 ; i < [array count] ; i++){
        NSString *sCert = array[i];
        
        NSArray *arrayCertInfo = [sCert componentsSeparatedByString:@":"];
//        NSString *sCertName = arrayCertInfo[0]; // 사용자 명
        NSString *sCertDN = arrayCertInfo[1]; // 사용자 DN
//        NSString *sUse =  arrayCertInfo[2]; // 용도 /구분
//        NSString *sIssue = arrayCertInfo[3]; // 발급자명
//        NSString *sIssueDN = arrayCertInfo[4]; // 발급자 DN
//        NSString *sExpire = arrayCertInfo[5]; // 만료여부
//        NSString *sExpireDate = arrayCertInfo[6]; // 만요일
//        NSString *sseries =  arrayCertInfo[7]; // 인증서 일련번호
        [arrayCert addObject:sCertDN];
    }
    
    return arrayCert;
}

- (NSArray*)getCertUserList{
    NSArray *array = [[SmartChampAPI instance] getUserCertList];
    
    NSMutableArray *arrayCert = [NSMutableArray array];
    for ( NSInteger i = 0 ; i < [array count] ; i++){
        NSString *sCert = array[i];
        
        NSArray *arrayCertInfo = [sCert componentsSeparatedByString:@":"];
        NSString *sCertName = arrayCertInfo[0]; // 사용자 명
//        NSString *sCertDN = arrayCertInfo[1]; // 사용자 DN
//        NSString *sUse =  arrayCertInfo[2]; // 용도 /구분
//        NSString *sIssue = arrayCertInfo[3]; // 발급자명
//        NSString *sIssueDN = arrayCertInfo[4]; // 발급자 DN
//        NSString *sExpire = arrayCertInfo[5]; // 만료여부
//        NSString *sExpireDate = arrayCertInfo[6]; // 만요일
//        NSString *sseries =  arrayCertInfo[7]; // 인증서 일련번호
        [arrayCert addObject:sCertName];
    }
    
    return arrayCert;
}

- (void)onCloseButton:(UIButton*)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)selectComboBox:(ComboBox*)box selectKey:(NSString*)key
{
    certDN = key;
}

- (void)onExportButton:(UIButton*)btn
{
    BOOL succes = [[SmartChampAPI instance] checkCertPwdDN:certDN password:certPwdTextField.text];
    if (succes){
        NSString *simpleNum = [NSString stringWithFormat:@"%@%@%@" , firstNumber.text , secondNumber.text , thirdNumber.text];
        
        NSString *sReturn = [[SmartChampAPI instance] exportCert:certDN simpleCertNum:simpleNum];
        NSArray *arrayReturn = [sReturn componentsSeparatedByString:@"`"];
        
        if ([arrayReturn[0] isEqualToString:@"Success"]){
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"알림"
                                                                           message:[arrayReturn objectAtIndex:1]
                                       preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault
                                           handler:^(UIAlertAction * action) {
                
            }];

            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
    }else{
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"알림"
                                                                       message:@"비밀번호가 틀렸습니다."
                                   preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault
                                       handler:^(UIAlertAction * action) {
            
        }];

        [alert addAction:defaultAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
