//
//  ChangeDeviceNamePopupView.m
//  OneCable
//
//  Created by nComz on 2017. 5. 12..
//  Copyright © 2017년 ntels. All rights reserved.
//

#import "ChangeDeviceNamePopupView.h"
#import "CustomTextField.h"
#import "CustomLabel.h"

#import "JDObject.h"
#import "RequestHandler.h"
#import "JDJSONModel.h"
#import "ValidateUtil.h"

@interface ChangeDeviceNamePopupView () <CustomTextFieldDelegate>
{
    
    BOOL changeDevicePopup;
    
}

@end

@implementation ChangeDeviceNamePopupView


- (id)initFromNib:(DeviceDetailModel*)detailModel{
    
    for (UIView *view in [CommonUtil nibViews:@"ChangeDeviceNamePopupView"]) {
        if ([view isKindOfClass:[ChangeDeviceNamePopupView class]]) {
            
            self = (ChangeDeviceNamePopupView *)view;
            self.deviceDetailModel = detailModel;
            
            NSLog(@"initFromNib : %@", detailModel);
    
            
            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;
            self.lblTitle.text = NSLocalizedString(@"이름 변경", @"이름 변경");
            
            NSString * prdName = [_deviceDetailModel.prdName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            NSString * prdUserName = [_deviceDetailModel.prdUserName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            
            if ([prdName isEqualToString: prdUserName] || [prdUserName isEqualToString:@""]) {
                _txtInputDeviceName.placeholder = @"새로운 이름";
            } else {
                _txtInputDeviceName.placeholder = _deviceDetailModel.prdUserName;
            }
            
            
            _txtInputDeviceName.keyboardType = UIKeyboardTypeDefault;
            _txtInputDeviceName.returnKeyType = UIReturnKeyDone;
            
            [self.imgTitleBar setImage:[UIImage imageNamed:@"img_popup_bg_head"]inset:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
            
            changeDevicePopup = NO;
        }
    }
    
    return self;
}

- (void)showChangeDevice:(DeviceModel*)deviceModel{
    
    [super show];
    
    _deviceModel = deviceModel;
    changeDevicePopup = YES;
    
    self.lblTitle.text = NSLocalizedString(@"홈허브 이름 설정", @"홈허브 이름 설정");
    
    _txtInputDeviceName.placeholder = _deviceModel.deviceName;
    
    [self.btnConfirm setTitle:NSLocalizedString(@"저장", @"저장") forState:UIControlStateNormal];
    [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];

}

- (void)didMoveToSuperview {
    if (!self.superview) {
        return;
    }
    //    _txtNickname.customTextFieldSuperview = CustomTextFieldSuperviewIsPopupContentView;
}

#pragma mark - UI Events
- (IBAction)btnConfirmTouched:(id)sender {

    [self requestDeviceChangeName:changeDevicePopup];
    
}

- (void) requestDeviceChangeName:(BOOL)isDevice {
    
    NSDictionary *parameters;
    
    if (_deviceModel != nil) {
        parameters = @{@"device_id": _deviceModel.deviceId,
                       @"prd_user_name" : _txtInputDeviceName.text.trim};
    }
    else {
        
        NSString *nodeName = [_txtInputDeviceName.text isEqualToString:@""] ? _deviceDetailModel.prdName : _txtInputDeviceName.text.trim;
        
        parameters =  @{@"device_id": _deviceDetailModel.deviceId,
                        @"node_id" : _deviceDetailModel.nodeId,
                        @"prd_user_name" : nodeName};
    }

    NSString *path = [[JDFacade facade] getUrlWithCustAndGroupID:API_PUT_DEVICE_INFO arguments:nil];
    
    [[RequestHandler handler] sendAsyncPutRequestAPIPath:path
                                              parameters:parameters
                                              modelClass:[JDJSONModel class]
                                              completion:^(id responseObject) {
                                                  
                                                  NSString *nodeName = [_txtInputDeviceName.text isEmptyString] ? _deviceDetailModel.prdName : _txtInputDeviceName.text;
    
                                                  
                                                  [self.delegate changeDeviceName:changeDevicePopup ? _txtInputDeviceName.text : nodeName];
                                                  [super btnCancelTouched:nil];
                                                  
                                              } failure:^(id errorObject) {
                                                  
                                                  JDErrorModel *error = (JDErrorModel *)errorObject;
                                                  [[JDFacade facade] alert:error.errorMessage];
                                              }];
}

#pragma mark - CustomTextField
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if ([textField isEqual:_txtInputDeviceName]) {
        [self btnConfirmTouched:nil];
    }
    return YES;
}


@end
