//
//  NewGroupPopupView.m
//  kneet
//
//  Created by Jason Lee on 4/28/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "CustomLabel.h"
#import "CustomTextField.h"

#import "NewGroupPopupView.h"
#import "RequestHandler.h"
#import "JDJSONModel.h"
#import "ThingsGroupAddViewController.h"
#import "DeviceModel.h"
#import "ThingsViewController.h"
#import "ValidateUtil.h"

@interface NewGroupPopupView () <CustomTextFieldDelegate> {

}

@end

@implementation NewGroupPopupView

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"NewGroupPopupView"]) {
        if ([view isKindOfClass:[NewGroupPopupView class]]) {
            self = (NewGroupPopupView *)view;
            //XIB의 경우, 현재 화면 사이즈로 맞춰줘야 함.
            self.frame = [UIScreen mainScreen].bounds;

            self.lblTitle.text = NSLocalizedString(@"새 그룹",nil);
            
            [self.btnConfirm setTitle:NSLocalizedString(@"만들기", @"만들기") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
            
            _txtGroupName.placeholder = NSLocalizedString(@"이름 입력", @"이름 입력");
        }
    }

    return self;
}

- (void)setGroup:(GroupsModel *)group {
    _group = group;

    _txtGroupName.text = _group.dvcgrpName;

    self.lblTitle.text = NSLocalizedString(@"그룹명 변경", @"그룹명 변경");
    [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
}

- (void)didMoveToSuperview {
    self.txtGroupName.delegate = self;
    self.txtGroupName.keyboardType = UIKeyboardTypeDefault;
    self.txtGroupName.returnKeyType = UIReturnKeyDone;
    self.txtGroupName.customTextFieldSuperview = CustomTextFieldSuperviewIsPopupContentView;
}

#pragma mark - Main Logic
- (void)requestAddNewGroup {
    //parameters
    NSDictionary *parameter = @{@"dvcgrp_name": _txtGroupName.text};

    NSString *path = [NSString stringWithFormat:API_POST_GROUP];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[GroupsModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }

        GroupsModel *group = (GroupsModel *)responseObject;

        if (group) {//API 성공 ,
            [super btnConfirmTouched:nil];

            //그룹에 장치 추가로 이동.
            ThingsGroupAddViewController *vc = (ThingsGroupAddViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsGroupAddViewController" storyboardName:@"Things"];
            vc.addedGroup = group;
            vc.groupList = ((ThingsViewController *)[JDFacade facade].currentViewController).groupList;

            [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestModifyGroupName {
    //parameters
    NSDictionary *parameter = @{@"change_dvcgrp_name": _txtGroupName.text};

    NSString *path = [NSString stringWithFormat:API_POST_GROUP_UPDATE, _group.dvcgrpId];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {

        _group.dvcgrpName = _txtGroupName.text;
        //리스트를 다시 로드함.
        [[JDFacade facade] toast:NSLocalizedString(@"그룹명이 변경되었습니다", @"그룹명이 변경되었습니다")];
        [super btnConfirmTouched:nil];

    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


#pragma mark - UI Events
- (void)btnConfirmTouched:(id)sender {
    [self endEditing:YES];

    //validate
    if (![ValidateUtil validateTextfiled:_txtGroupName type:ValidateTypeNull title:NSLocalizedString(@"그룹명", @"그룹명")]) {
        return;
    }

    if (!_group) {
        [self requestAddNewGroup];
    } else {
        [self requestModifyGroupName];
    }
}

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

@end
