//
//  ViewController.m
//  EugineAPISample
//
//  Created by aaab on 2022/12/23.
//

//HelveticaNeue-Regular,
//HelveticaNeue-Thin,
//HelveticaNeue-UltraLight,
//HelveticaNeue-Light,
//HelveticaNeue-Medium,
//HelveticaNeue-SemiBold,
//HelveticaNeue-Bold

#import "ViewController.h"
#import "SmartChampReal.h"
#import "SmartChampAPI.h"
#import "LoginViewController.h"
#import "INetInitDelegate.h"
#import "INetLoginDelegate.h"
#import "SmartChampDefs.h"
#import "AlarmItemChegyul.h"
#import "iToast.h"
#import "Util.h"
#import "Reachability.h"
#import "ComUtil.h"

static NSInteger g_nNetworkStatus = -1; // 2020.01.22. 네트워크 상태 저장
static BOOL g_isNeedReconnect = NO; // 2020.01.22. 재접속 필요 여부 플래그

@interface ViewController () <INetLogoutDelegate , INetInitDelegate , INetLoginDelegate >
{
    NSArray *arrayViewController;
    SmartChampAPI *champAPI;
    Reachability *internetReach;
}
@end

@implementation ViewController



- (void)networkCheck
{
   [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    internetReach = [Reachability reachabilityForInternetConnection];
    [internetReach startNotifier];
    [self updateInterfaceWithReachability:internetReach];
}



- (void)reachabilityChanged:(NSNotification *)note
{
    Reachability *curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self updateInterfaceWithReachability:curReach];
}


- (void)updateInterfaceWithReachability:(Reachability *)curReach
{
    if(curReach == internetReach)
    {
        NetworkStatus netStatus = [curReach currentReachabilityStatus];

        NSString *statusString = @"";
        switch (netStatus)
        {
            case NotReachable:
                statusString = @"Access Not Available";
                break;
            case ReachableViaWiFi:
                statusString = @"Reachable WiFi";
                break;
            case ReachableViaWWAN:
                statusString = @"Reachable WWAN";
                break;
            default:
                break;
        }

        NSLog(@"Net Status changed. current status=%@ ", statusString);



        // 네트워크 상태에 따라 처리
        if(netStatus == NotReachable)
        {
            g_isNeedReconnect = YES;
//            [self showAlert];
//            return;
        }
        
        if(g_nNetworkStatus >= 0 && g_nNetworkStatus != netStatus)
        {
            g_isNeedReconnect = YES;
        }
        g_nNetworkStatus = netStatus;
        
        if(g_isNeedReconnect)
        {
            g_isNeedReconnect = NO;
            [self startConnect];
        }
    }
}

- (void)dealloc
{
    
    // OpenAPI 종료
    [SmartChampAPI releaseOpenAPI];
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [self showLoginViewController];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
//    NSString* strVersionName  = [[NSBundle mainBundle] objectForInfoDictionaryKey:(NSString *)kCFBundleVersionKey]; //
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    BOOL isRealSearch = [[ComUtil getString:@"common.real.server" basic:@"0"] boolValue];
    
    NSString *newText = [NSString stringWithFormat:@"%@ (%@ 서버 접속중)" , version , isRealSearch ? @"운영" : @"테스트"];
    
    UILabel *verlabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 50, CGRectGetWidth(self.view.frame), 30)];
    [verlabel setText:newText];
    [verlabel setFont:[Util fontType:BOLD size:13]];
    [verlabel setTextColor:[UIColor systemBlueColor]];
    [self.view addSubview:verlabel];

//        NSArray *arrFileName = [fileName componentsSeparatedByString:@"."];
//        if ( [arrFileName count] > 1){
//            NSString *sFileName = [arrFileName objectAtIndex:0];
//            NSString *sLastType = [arrFileName objectAtIndex:1];
//
//            return [bundle pathForResource:sFileName ofType:sLastType inDirectory:subpath];
//        }else{
//            return [bundle pathForResource:fileName ofType:@"" inDirectory:subpath];
//        }
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(NotifyChegyulAlram:) name:notifyChegyulAlram object:nil];
    
    
//    for (NSString *sName in [UIFont familyNames]) {
//        NSLog(@"sName [%@]" , sName);
//    }
//
//    NSArray *arrayFonts= [UIFont fontNamesForFamilyName:@"Helvetica Neue"];
    
    
    //    connection = [[ConnectionManager alloc] initWithDelegate:self];
    // Do any additional setup after loading the view.
    arrayViewController = [NSArray arrayWithObjects:@"" ,@"TransactionViewController" ,  @"StockPriceViewController" , @"FuturePriceViewController", @"OverseaStockViewController" , @"CondSearchViewController" , nil];
    
    NSArray *arrayTitle = [NSArray arrayWithObjects:@"로그인/로그아웃" , @"TR 테스트" , @"주식 현재가" , @"선물 옵션현재가" , @"해외주식 현재가" ,@"조건 검색" ,  nil];
    
    CGFloat selfWidth = CGRectGetWidth(self.view.frame);
    CGFloat selfHeight = CGRectGetHeight(self.view.frame) - 200;
    
    CGFloat yPos = 100;
    CGFloat oneBtnHeight = selfHeight / [arrayTitle count];
    CGSize btnSize = CGSizeMake(selfWidth - 60, oneBtnHeight - 30);
    NSInteger nIndex = 0;
    for (NSString *title in arrayTitle) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark];
        [btn setFrame:CGRectMake(30, yPos, btnSize.width, btnSize.height)];
        [btn setTitle:title forState:UIControlStateNormal];
        [btn setTitle:title forState:UIControlStateSelected];
        [btn setTitle:title forState:UIControlStateHighlighted];
        [btn setTitle:title forState:UIControlStateDisabled];
        [btn addTarget:self action:@selector(onButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
        [btn setTag:nIndex];
        [self.view addSubview:btn];
        yPos += oneBtnHeight;
        nIndex++;
    }
    
    if (isRealSearch){
        [[SmartChampAPI instance] setDevMode:SERVER_MODE_REAL];
    }else{
        [[SmartChampAPI instance] setDevMode:SERVER_MODE_DEV];
    }
    [self startConnect];
    [self networkCheck];
    [self performSelector:@selector(showLoginViewController) withObject:nil afterDelay:0.1];
}

- (void)startConnect
{
    [[SmartChampAPI instance] setInitDelegate:self];
    [[SmartChampAPI instance] startConnect];
}


- (void)showLoginViewController{
    if ([[SmartChampAPI instance] getLoginType] == LOGIN_MODE_NONE)
    {
        LoginViewController *controller = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
        [self presentViewController:controller animated:YES completion:^{
            
        }];
    }
}

- (void)onButtonTouchUpInside:(UIButton*)sender
{
    if (sender.tag == 0){
        LOGIN_MODE mode = [[SmartChampAPI instance] getLoginType];
        if ([[SmartChampAPI instance] getLoginType] == LOGIN_MODE_NONE)
        {
            LoginViewController *controller = [[LoginViewController alloc] initWithNibName:nil bundle:nil];
            [self presentViewController:controller animated:YES completion:^{
                
            }];
        }else{
            [[SmartChampAPI instance] setLogoutDelegate:self];
            [[SmartChampAPI instance] logoutUser];
        }
    }else{
        NSString *sClass = [arrayViewController objectAtIndex:sender.tag];
        
        UIViewController *controller = [[NSClassFromString(sClass) alloc] initWithNibName:nil bundle:nil];
        [self presentViewController:controller animated:YES completion:^{
            
        }];
    }
}

- (void)xanofefaew
{
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"알림"
                                                                   message:@"OBC1207Q 서비스 호출에 오류가 발생했습니다.."
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
        [self dismissViewControllerAnimated:YES completion:^{
        }];
    }];
    
    [alert addAction:defaultAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - initNetDelegate Method


- (void)onSessionConnecting
{
    
}

/**
 * 서버 접속 완료
 * @param isSuccess 성공여부
 * @param strErrorMsg 에레메세지
 */
- (void)onSessionConnected:(BOOL)isSuccess error:(NSString*)strErrorMsg
{
    if ( isSuccess ){
        [self showLoginViewController];
    }else{
//        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"알림"
//                                                                       message:strErrorMsg
//                                                                preferredStyle:UIAlertControllerStyleAlert];
//
//        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"확인" style:UIAlertActionStyleDefault
//                                                              handler:^(UIAlertAction * action) {
//
//        }];
//
//        [alert addAction:defaultAction];
//        [self presentViewController:alert animated:YES completion:nil];
    }
}

/**
 * API 버젼체크
 * param nCheckState 업데이트 필요 유형 ( -1 : 오류, 0 : 필요없음, 1 : 권고, 2 : 강제업데이트 )
 * param sUpdateInfo
 */
- (void)onAPIVersionState:(NSInteger)nCheckState update:(NSString*)sUpdateInfo
{
    
}

/**
 * 파일 다운로드 작업 상태
 * param nState 다운로드 상태 ( 0 : 진행중, 1 : 상태알림, 2 : 완료 )
 * param nIndex 진행상태
 * param nCount 전체갯수
 * param sMessage 메시지 ( 상태 알림 )
 */
- (void)onUpdateDownloadState:(NSInteger)nState index:(NSInteger)nIndex count:(NSInteger)nCount message:(NSString*)sMessage
{
    
}


/**
 * 마스터 로드 작업 상태
 * @param nState 로드 상태 ( 0 : 시작, 1 : 완료 )
 */
- (void)onMasterLoadState:(NSInteger)nState
{
    
}


/**
 * 모든 초기화 작업 완료된 상태
 */
- (void) onInitFinished{
    
}

/**
 * 재접속
 */
- (void) onRequiredRefresh
{
    
}

#pragma mark - ILogoutDelegate Method
- (void)onLogoutFinished
{
    [[iToast instance] showText:@"로그아웃 되었습니다." duration:iToastDurationLong gravity:iToastGravityBottom];
    [self showLoginViewController];
}


- (void)NotifyChegyulAlram:(NSNotification*)noti
{
    AlarmItemChegyul *chegyul =  (AlarmItemChegyul*)[noti object];
//    chegyul.m_strDataSect;                    // 자료구분. 0:주문접수,1:체결,2:확인,3:주문전송
    
    NSString *sMessage = nil;
    if ([chegyul.m_strDataSect isEqualToString:@"0"]){
        sMessage = [NSString stringWithFormat:@"주문번호 [%@] 종목 [%@] 수량:%@ 가격:%@ 이 접수 되었습니다.", chegyul.m_strOrdNo , chegyul.m_strItemNm , chegyul.m_strQty , chegyul.m_strUprc];
    }else if ([chegyul.m_strDataSect isEqualToString:@"1"]){
        sMessage = [NSString stringWithFormat:@"주문번호 [%@] 종목 [%@] 수량:%@ 가격:%@ 이 체결 되었습니다.", chegyul.m_strOrdNo , chegyul.m_strItemNm , chegyul.m_strQty , chegyul.m_strUprc];
    }
    
    if (sMessage != nil){
        [[iToast instance] showText:sMessage duration:iToastDurationLong gravity:iToastGravityBottom];
    }
    
}

@end
