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

#import "SignUpQuizSetViewController.h"
#import "CustomTextField.h"
#import "CustomDatePopupView.h"
#import "RequestHandler.h"
#import "ImageUtil.h"
#import "IDSetViewController.h"

/**
 해당 메뉴는 마스터만 출력
 **/
@interface SignUpQuizSetViewController () <CustomTextFieldDelegate,dismissPopupViewDelegate> {
    
    DataSelectListModel *_quizList; // 퀴즈 목록 모델
    DataSelectModel *_selectedQuiz; // 선택 한 퀴즈
    CustomDatePopupView *_popDate;  // 정답 입력 팝업
    NSString *answer;               // 입력한 정답
}

@end

@implementation SignUpQuizSetViewController
@synthesize signUpModel;

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initUI];
}

// 퀴즈 목록을 가져옴
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestQuizList];
    
}

// UI 설정
- (void)initUI {
    
    [self.navigationController.navigationBar setHidden:YES];
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    signUpModel = [[SignUpModel alloc]init];
    
    [_lblStep setColor:kUITextColor03 text:[NSString stringWithFormat:@"%@", @"/ 5"]];

    answer = @"";
    _btnNext.enabled = NO;
    [self showDirectInputArea:NO];
    
    _txtQuizSelect.delegate = self;
    _txtSelfQuiz.delegate = self;
    
    _txtQuizSelect.keyboardType = UIKeyboardTypeDefault;
    _txtQuizSelect.returnKeyType = UIReturnKeyDone;
    
    _txtSelfQuiz.keyboardType = UIKeyboardTypeDefault;
    _txtSelfQuiz.returnKeyType = UIReturnKeyDone;
    
    _txtQuizSelect.placeholder = @"퀴즈 선택";

}

// 선택입력,사용자 입력 여부에 따라 뷰 높이 값 설정
-(void)showDirectInputArea:(BOOL)isShow
{
    _viewSelfQuiz.hidden = !isShow;
    
    if(_viewSelfQuiz.isHidden){
        _viewHeight.constant = 0;
    } else{
        _viewHeight.constant = 177.0f;
    }
}

// 다음 버튼 활성화 여부 및 선택한 퀴즈 입력 설정
- (void)updateUI {
    _btnNext.enabled = [self isValidRequestInfo];
    
    if (_selectedQuiz != nil) {
        QuizModel *info = (QuizModel *)_selectedQuiz.value;
        [self showDirectInputArea:[info isUserEditQuiz]];
        _txtQuizSelect.text = _selectedQuiz.title;
    } else {
        [self showDirectInputArea:NO];
    }
}

// 퀴즈 목록 요청
- (void)requestQuizList {
    
    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_INVITE_QUIZ];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[QuizListModel class] completion:^(id responseObject) {
        
        QuizListModel *quizList = (QuizListModel *)responseObject;
        
        //NSLog(@"Response : %@", responseObject);
        _quizList = [[DataSelectListModel alloc] init];
        _quizList.title = @"퀴즈 선택";
        
        for (QuizModel *info in quizList.quizList) {
            DataSelectModel *data = [[DataSelectModel alloc] init];
            data.title = info.quiz;
            data.value = info;
            [_quizList.list addObject:data];
        }
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
    
}

// 사용자가 입력한 퀴즈 저장 후 아이디,비밀번호 설정 메뉴로 이동
- (void)masterQuizSet{
    QuizModel *quizInfo = (QuizModel *)_selectedQuiz.value;
    NSLog(@"Quiz Info : %@", quizInfo);
    
    NSString *quiz = quizInfo.quiz;
    if (quizInfo.isUserEditQuiz) {
        quiz = [_txtSelfQuiz.text trim];
    }

    SignUpModel *signUpInfo = [[SignUpModel alloc]init];
    signUpInfo = signUpModel;
    signUpInfo.quiz = quiz;
    signUpInfo.quizId = quizInfo.quizId;
    signUpInfo.statusCode = quizInfo.statusCode;
    signUpInfo.answer = answer;
    signUpInfo.phone = _phoneNum;
    
    IDSetViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"IDSetViewController" storyboardName:@"SignUp"];
    
    vc.signUpModel = signUpInfo;

    [self.navigationController pushViewController:vc animated:YES];
}

// 퀴즈 목록가져온 후 선택한 퀴즈 입력 설정
-(void)showQuizList{
    [[JDFacade facade] selectDatas:self listInfo:_quizList completion:^(DataSelectModel *seleced) {
        _selectedQuiz = seleced;
        _txtQuizSelect.text = _selectedQuiz.title;
        [self updateUI];
        
    }];
}

// 메뉴 닫기
- (IBAction)btnCancelTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

// 다음 버튼 터치시 사용자가 입력한 퀴즈 저장 후 메뉴이동
- (IBAction)btnNextTouched:(id)sender {
    [self masterQuizSet];
}

// 정답 날짜 입력 팝업 출력 및 입력한 날짜 가져옴
- (IBAction)btnInputQuizTouched:(id)sender {
    if (_popDate == nil) {
        _popDate = [[CustomDatePopupView alloc] initWithTitle:@"정답 날짜 입력"];
        _popDate.delegate = self;
    }
    
    [_popDate showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            NSLog(@"Input Date : %@%@%@", _popDate.txtYear.text, _popDate.txtMonth.text, _popDate.txtDay.text);
            
            NSString *date = [NSString stringWithFormat:@"%@%@%@",_popDate.txtYear.text,_popDate.txtMonth.text,_popDate.txtDay.text];
            
            answer = date;
            if ([date isEqualToString:@""]) {
                [_btnInputQuizAnswer setTitle:[CommonUtil currentDate2] forState:UIControlStateNormal];
                answer = [CommonUtil currentDate3];
            NSLog(@"Current Date : %@",answer);
            } else {
                NSString *date = [NSString stringWithFormat:@"%@ / %@ / %@",_popDate.txtYear.text,_popDate.txtMonth.text,_popDate.txtDay.text];
                [_btnInputQuizAnswer setTitle:date forState:UIControlStateNormal];
            }
            [_btnInputQuizAnswer setBackgroundImage:[UIImage imageNamed:@"img_input_round_bg_active"] forState:UIControlStateNormal];
            [_btnInputQuizAnswer setTitleColor:kUITextColor01 forState:UIControlStateNormal];
        }
    }];
}

// (delegate) 팝업이 꺼졌을 경우 호출
- (void)dismissPopupView{
    _btnNext.enabled = [self isValidRequestInfo];
    if ([[_btnInputQuizAnswer titleForState:UIControlStateNormal] isEqualToString:_btnInputQuizAnswer.placeHolder])
    {
        _btnNext.enabled = NO;
    }
}

// 다음버튼 활성화 여부 체크
- (BOOL)isValidRequestInfo {
    BOOL result = YES;
    
    QuizModel *quizInfo = (_selectedQuiz != nil) ? (QuizModel *)_selectedQuiz.value : nil;
    
    if (result && quizInfo == nil)
    {
        result = NO;
    }
    
    if (result && quizInfo.isUserEditQuiz)
    {
        if ([[_txtSelfQuiz.text trim] isEmptyString])
        {
            result = NO;
        }
    }

    if ([_btnInputQuizAnswer.titleLabel.text isEqualToString:@"정답 날짜 입력"])
    {
        result = NO;
    }
    return result;
}

// 퀴즈선택 TextField 터치시 퀴즈 목록 출력
-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:_txtQuizSelect]) {
        [self showQuizList];
        return NO;
    }
    return YES;
}

// 입력 된 퀴즈 여부에 따라 다음버튼 활성화 설정
- (void)textFieldDidEndEditing:(UITextField *)textField{
   
    _btnNext.enabled = _txtSelfQuiz.text.length > 0;
    
    if ([_btnInputQuizAnswer.titleLabel.text isEqualToString:@"정답 날짜 입력"])
    {
        _btnNext.enabled = NO;
    }
}

// TextField Done 버튼 설정 
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

@end
