//
//  SettingView.m
//  SKCore
//
//  Created by jungeol.park on 2014. 10. 1..
//  Copyright (c) 2014 ACCVUER. All rights reserved.
//

#import "EngineerModeSettingView.h"
#import "UIViewController+MJPopupViewController.h"
#import "MainPagingScrollViewController.h"

#define TEXT_FIELD_VALUE_NOT_CHANGED -1;

@implementation EngineerModeSettingView

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self)
    {
        
    }
    return self;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

-(void)dealloc
{
    [self removeKeyboardNoti];
}

-(void)addKeyboardNoti
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)removeKeyboardNoti
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


////////////////////
//    NSDictionary *common = [[NSDictionary alloc] initWithObjectsAndKeys:
//                            @"1", @"Autorepeat",
//                            @"5", @"Idel",
//                            @"1", @"Count",
//                            nil];
//    NSDictionary *download = [[NSDictionary alloc] initWithObjectsAndKeys:
//                              @"20", @"Filesize",
//                              @"2", @"Count",
//                              @"3", @"Session",
//                              @"20000000", @"Time",
//                              nil];
//    NSDictionary *upload = [[NSDictionary alloc] initWithObjectsAndKeys:
//                            @"20", @"Filesize",
//                            @"2", @"Count",
//                            @"3", @"Session",
//                            @"20000000", @"Time",
//                            nil];
//    NSDictionary *latency = [[NSDictionary alloc] initWithObjectsAndKeys:
//                             @"500000", @"Interval",
//                             @"30000000", @"Time",
//                             @"2000000", @"Timeout",
//                             @"60", @"numberOfPacket",
//                             nil];
//    NSDictionary *scenario = [[NSDictionary alloc] initWithObjectsAndKeys:
//                              common, @"Common",
//                              download, @"Download",
//                              upload, @"Upload",
//                              latency, @"Latency",
//                              nil];

-(void)saveModifiedSetting
{
    NSDictionary *modifiedScenario = [[NSDictionary alloc] initWithObjectsAndKeys:
                              m_commonInfoDic, @"Common",
                              m_downloadInfoDic, @"Download",
                              m_uploadInfoDic, @"Upload",
                              m_latencyInfoDic, @"Latency",
                              nil];
    
    BOOL isSuccess = [SKGlobalMethods saveModifiedScenarioDic:modifiedScenario];
    
    if(isSuccess)
    {
        [self reloadScenarioDic];
        
        if ([SKAAppDelegate getAppDelegate].mainPagingScrollVC.m_runTestView != nil)
            [[SKAAppDelegate getAppDelegate].mainPagingScrollVC.m_runTestView reloadAutoRepeatInfo];
    }
    else
    {
        // save file error
        UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"information"
                                      message:@"setting file save error"
                                      delegate:nil
                                      cancelButtonTitle:@"Ok"
                                      otherButtonTitles:nil];
        [alert show];
    }
}

-(void)initViews
{
    [self reloadScenarioDic];
    
    // init text field
    self.idleTimeTextField.placeholder = @"1 ~ 1440 min";
    self.repeatCountTextField.placeholder = @"1 ~ 9999";

    [self addKeyboardNoti];
}

-(void)updateAutoRepeatCheckBoxUi
{
    if (m_isAutoRepeat_saved == YES)
    {
        [self.autoRepeatCheckedBoxImage setHidden:NO];
        [self.autoRepeatUncheckedBoxImage setHidden:YES];
        [self.idleTimeTextField setEnabled:YES];
        self.idleTimeTextField.alpha = 1.0f;
        [self.repeatCountTextField setEnabled:YES];
        self.repeatCountTextField.alpha = 1.0f;
    }
    else
    {
        [self.autoRepeatCheckedBoxImage setHidden:YES];
        [self.autoRepeatUncheckedBoxImage setHidden:NO];
        [self.idleTimeTextField setEnabled:NO];
        self.idleTimeTextField.alpha = 0.5f;
        [self.repeatCountTextField setEnabled:NO];
        self.repeatCountTextField.alpha = 0.5f;
    }
}

-(void) reloadScenarioDic
{
    // load auto-repeat value from file
    m_scenarioDic = [[SKAAppDelegate getAppDelegate].testSchedule_new getScenarioDic];
    
    if(m_scenarioDic == nil)
        return;

    m_commonInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[m_scenarioDic objectForKey:@"Common"]];
    m_downloadInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[m_scenarioDic objectForKey:@"Download"]];
    m_uploadInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[m_scenarioDic objectForKey:@"Upload"]];
    m_latencyInfoDic = [[NSMutableDictionary alloc] initWithDictionary:[m_scenarioDic objectForKey:@"Latency"]];
    
    m_isAutoRepeat_saved = [[m_commonInfoDic objectForKey:@"Autorepeat"] boolValue];
    m_idleTime_saved = [[m_commonInfoDic objectForKey:@"Idel"] intValue];
    m_repeatCount_saved = [[m_commonInfoDic objectForKey:@"Count"] intValue];;

    m_isAutoRepeatModified = NO;
    
    self.idleTimeTextField.text = [NSString stringWithFormat:@"%d min", m_idleTime_saved];
    self.repeatCountTextField.text = [NSString stringWithFormat:@"%d", m_repeatCount_saved];
    
    // checkBox
    [self updateAutoRepeatCheckBoxUi];
}

#pragma mark - button action
- (IBAction)checkBoxClicked:(id)sender
{
    BOOL isAutoRepeat = ! m_isAutoRepeat_saved;
    
//    m_isAutoRepeatModified = YES;
    [m_commonInfoDic setObject:[NSString stringWithFormat:@"%d", isAutoRepeat] forKey:@"Autorepeat"];
    [self saveModifiedSetting];
}

- (IBAction)callDownloadSettingPopup:(id)sender
{
    // close keyboard
    [self tapDetected:nil];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    DLULSettingPopupViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"DLULSettingPopupViewController"];
    
    vc.delegate = self;
    vc.isDownLoad = YES;
    vc.configInfoDic = m_downloadInfoDic;
    
    if([SKAAppDelegate getAppDelegate].mainPagingScrollVC != nil)
        [[SKAAppDelegate getAppDelegate].mainPagingScrollVC presentPopupViewController:vc animationType:MJPopupViewAnimationSlideBottomBottom isEnableBgTouch:NO];
    
    [self removeKeyboardNoti];
}

- (IBAction)callUploadSettingPopup:(id)sender
{
    // close keyboard
    [self tapDetected:nil];
    
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    DLULSettingPopupViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"DLULSettingPopupViewController"];
    
    vc.delegate = self;
    vc.isDownLoad = NO;
    vc.configInfoDic = m_uploadInfoDic;
    
    if([SKAAppDelegate getAppDelegate].mainPagingScrollVC != nil)
        [[SKAAppDelegate getAppDelegate].mainPagingScrollVC presentPopupViewController:vc animationType:MJPopupViewAnimationSlideBottomBottom isEnableBgTouch:NO];
    
    [self removeKeyboardNoti];
}

#pragma mark - DLULSettingPopupViewDelegate
-(void)dismissDLULSettingPopupViewWithModifiedDic:(NSDictionary *)dic withIsDownload:(BOOL)isDownload
{
    if (isDownload)
    {
        m_downloadInfoDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
    }
    else
    {
        m_uploadInfoDic = [[NSMutableDictionary alloc] initWithDictionary:dic];
    }
    
    [self saveModifiedSetting];
    
    [[SKAAppDelegate getAppDelegate].mainPagingScrollVC dismissPopupViewControllerWithanimationType:MJPopupViewAnimationSlideBottomBottom];
    [self removeKeyboardNoti];
}

-(void)dismissDLULSettingPopupView
{
    [[SKAAppDelegate getAppDelegate].mainPagingScrollVC dismissPopupViewControllerWithanimationType:MJPopupViewAnimationSlideBottomBottom];
    
    [self addKeyboardNoti];
}

#pragma mark - text Field

-(void)textFieldDidBeginEditing:(UITextField *)textField
{
    textField.text = @"";
    
    if (tgr == nil)
    {
        tgr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapDetected:)];
        tgr.numberOfTapsRequired = 1;
        [self addGestureRecognizer:tgr];
    }
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if(tgr != nil)
    {
        [self removeGestureRecognizer:tgr];
        tgr = nil;
    }
}

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSString *text = textField.text;
    
    if ([textField isEqual:self.idleTimeTextField])
    {
        if (text.length == 0)
            textField.text = [NSString stringWithFormat:@"%d min", m_idleTime_saved];
        else
        {
            int v = [text intValue];
            if(v < 1 || v > 1440)
            {
                [self showInvalidInputAlretWithMsg:@"Please enter a valid value: 1 ~ 1440"];
                return NO;
            }
            else
            {
                textField.text = [NSString stringWithFormat:@"%d min", v];
                if (v != m_idleTime_saved)
                {
                    m_isAutoRepeatModified = YES;
                    [m_commonInfoDic setObject:[NSString stringWithFormat:@"%d", v] forKey:@"Idel"];
                }
                
            }
        }
        
    }
    else// if ([textField isEqual:self.repeatCountTextField])
    {
        if (text.length == 0)
            textField.text = [NSString stringWithFormat:@"%d", m_repeatCount_saved];
        else
        {
            int v = [text intValue];
            if(v < 1 || v > 9999)
            {
                [self showInvalidInputAlretWithMsg:@"Please enter a valid value: 1 ~ 9999"];
                return NO;
            }
            else
            {
                if (v != m_repeatCount_saved)
                {
                    m_isAutoRepeatModified = YES;
                    [m_commonInfoDic setObject:[NSString stringWithFormat:@"%d", v] forKey:@"Count"];
                }
            }
        }
    }
    
    return YES;
}

-(void)tapDetected:(UIGestureRecognizer *)sender
{
    [self.idleTimeTextField resignFirstResponder];
    [self.repeatCountTextField resignFirstResponder];
}

-(void)keyboardWillShow:(NSNotification *)noti
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:LockMainPagingScrollViewNotification object:nil];
    
    NSDictionary *keyboardInfo = [noti userInfo];
    NSValue *keyboardFrameBegin = [keyboardInfo valueForKey:UIKeyboardFrameBeginUserInfoKey];
    CGRect keyboardFrameBeginRect = [keyboardFrameBegin CGRectValue];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0.0, -keyboardFrameBeginRect.size.height);
    [self setTransform:transform];
    [UIView commitAnimations];
}

-(void)keyboardWillHide:(NSNotification *)noti
{
    
    [[NSNotificationCenter defaultCenter] postNotificationName:UnLockMainPagingScrollViewNotification object:nil];
    
    if (m_isAutoRepeatModified)
        [self saveModifiedSetting];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.25];
    CGAffineTransform transform = CGAffineTransformMakeTranslation(0.0, 0.0);
    [self setTransform:transform];
    [UIView commitAnimations];
}

-(void)showInvalidInputAlretWithMsg:(NSString *)alretMsg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"information", nil)
                                                    message:alretMsg
                                                   delegate:nil
                                          cancelButtonTitle:NSLocalizedString(@"MenuAlert_OK", nil)
                                          otherButtonTitles:nil];
    [alert show];
}

@end
