//
//  StartHomeViewController.m
//  kneet
//
//  Created by Jason Lee on 4/23/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"
#import "RequestHandler.h"

#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomTextField.h"

#import "StartHomeViewController.h"

#import "ValidateUtil.h"
#import "CustomAlertView.h"



@interface StartHomeViewController () <CustomTextFieldDelegate> {

}
@end


#pragma mark - Class Definition

@implementation StartHomeViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    _txtHomeName.delegate = self;
    _txtHomeName.keyboardType = UIKeyboardTypeDefault;
    _txtHomeName.returnKeyType = UIReturnKeyDone;
    _txtHomeName.customTextFieldSuperview = CustomTextFieldSuperviewIsScrollView;
}

- (void)initUI {
    

    if (_canGoBack) {
        _btnNext.hidden = YES;
        _btnSNext.hidden = _btnCancel.hidden =  NO;
    }
    
    //Localization
    _lblTitle.text = NSLocalizedString(@"시작합니다", @"시작합니다");
    _txtHomeName.placeholder = NSLocalizedString(@"홈 이름", @"홈 이름");
    [_btnNext setTitle:NSLocalizedString(@"다음", @"다음") forState:UIControlStateNormal];
    [_btnSNext setTitle:NSLocalizedString(@"다음", @"다음") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {
    _lblHomeDesc.text = [NSString stringWithFormat:NSLocalizedString(@"%@님의 새로운 홈에 이름을 붙여주세요", @"%@님의 새로운 홈에 이름을 붙여주세요"), [JDFacade facade].loginUser.nickname];
}

#pragma mark - Main Logic
- (void)requestRegisterHomeGroup {


    //parameters
    NSDictionary *parameter = @{@"homegrp_name": _txtHomeName.text};

    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP];

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

        LoginModel *result = (LoginModel *) responseObject;

        if (result) {//API 성공 ,
            //TODO : home group id
            [[JDFacade facade] toast:NSLocalizedString(@"등록되었습니다", @"등록되었습니다")];
            [JDFacade facade].tmpHomegrpName = _txtHomeName.text;

            UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeLocationViewController" storyboardName:@"SignUp"];
            [[JDFacade facade] presentViewControllerByPush:vc pvc:self];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


#pragma mark - UI Events
- (IBAction)btnCreateHomeTouched:(id)sender {
    [self.view endEditing:YES];
    //validate
#ifdef DEBUG
    if ([_txtHomeName.text isEmptyString]) {
        _txtHomeName.text = @"테스트홈";
    }
#else
    if (![ValidateUtil validateTextfiled:_txtHomeName type:ValidateTypeNull title:NSLocalizedString(@"홈 이름", @"홈 이름")]) {
        return;
    }
#endif

    [JDFacade facade].tmpHomegrpName = _txtHomeName.text;


    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"HomeLocationViewController" storyboardName:@"SignUp"];
    UINavigationController *nc = [[UINavigationController alloc] init];
    nc.viewControllers = @[vc];

    [[JDFacade facade] presentViewControllerByPush:nc pvc:self];
}

- (IBAction)btnCancelTouched:(id)sender {
    
    if ([JDFacade facade].loginUser.homegrpList.count == 0) {//현재 홈이 없을 경우,
        CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:NSLocalizedString(@"홈 만들기를 취소하면 서비스를 더 이상 이용할 수 없습니다\n취소하고 로그아웃 할까요?", @"홈 만들기를 취소하면 서비스를 더 이상 이용할 수 없습니다\n취소하고 로그아웃 할까요?") delegate:nil OKButtonTitle:NSLocalizedString(@"확인", @"확인") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
        [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {//OK
                
                [[JDFacade facade] logout];
                return;
            }
        }];
    } else {
        [[JDFacade facade] dismissViewControllerByPush:self];
    }
}

#pragma mark - CustomTextField

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self btnCreateHomeTouched:nil];

    return YES;
}



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


@end
