//
//  MobileCapPopupViewController.m
//  SKCore
//
//  Created by KSW on 2015. 1. 26..
//  Copyright (c) 2015 SamKnows. All rights reserved.
//

#import "MobileCapPopupViewController.h"

@interface MobileCapPopupViewController ()

@end

@implementation MobileCapPopupViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    m_dataCap = [SKGlobalMethods loadMobileDataCap];
    self.mobileCapTextField.text = [NSString stringWithFormat:@"%d MB", m_dataCap];
}

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

- (IBAction)okButtonClicked:(id)sender
{
    [self tapDetected:nil];
    
    [SKGlobalMethods saveMobileDataCap:m_dataCap];
    
    [self.delegate dismissMobileCapPopupView];
}

- (IBAction)cancelButtonClicked:(id)sender
{
    [self tapDetected:nil];
    
    [self.delegate dismissMobileCapPopupView];
}

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

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

-(BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    NSString *text = textField.text;
    
    if (text.length == 0)
    {
        textField.text = [NSString stringWithFormat:@"%d MB", MOBILE_DATA_CAP_DEFUALT];
    }
    else
    {
        int v = [text intValue];
        textField.text = [NSString stringWithFormat:@"%d MB", v];
        m_dataCap = v;
    }
    
    return YES;
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    if(tgr != nil)
    {
        if(self.view.superview != nil)
            [self.view.superview removeGestureRecognizer:tgr];
        else
            [self.view removeGestureRecognizer:tgr];
        
        tgr = nil;
    }
}
@end
