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

#import "QuizSetViewController.h"

#import "RequestHandler.h"
#import "CustomButton.h"
#import "CustomTextField.h"
#import "CustomDatePopupView.h"
#import "ChangeEmailPopupView.h"
#import "CommonUtil.h"
#import "ImageUtil.h"

@interface QuizSetViewController () <CustomTextFieldDelegate>{
    
    DataSelectListModel *_quizList;
    DataSelectModel *_selectedQuiz;
    CustomDatePopupView *_popDate;
    NSString *answer;
}

@end

@implementation QuizSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initUI];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requestInviteQuizList];
    
}
- (void)initUI{
    answer = @"";
    _btnConfirm.enabled = NO;
    [self showDirectInputArea:NO];
    
    _txtQuizSelect.delegate = self;
    _txtSelfQuiz.delegate = self;
    
    _txtQuizSelect.keyboardType = UIKeyboardTypeDefault;
    _txtQuizSelect.returnKeyType = UIReturnKeyDone;
    
    _txtQuizSelect.placeholder = @"퀴즈 선택";
//    _txtQuizSelect.customTextFieldSuperview = CustomTextFieldSuperviewIsContentView;
}

-(void)showDirectInputArea:(BOOL)isShow
{
    _viewSelfQuiz.hidden = !isShow;
    
    if(_viewSelfQuiz.isHidden){
        _viewHeight.constant = 0;
    } else{
        _viewHeight.constant = 224.0f;
    }
}

- (void)updateUI {
    _btnConfirm.enabled = [self isValidRequestInfo];
    
    if (_selectedQuiz != nil) {
        QuizModel *info = (QuizModel *)_selectedQuiz.value;
        [self showDirectInputArea:[info isUserEditQuiz]];
        _txtQuizSelect.text = _selectedQuiz.title;
    } else {
        [self showDirectInputArea:NO];
    }
}

-(void)showQuizList{
    [[JDFacade facade] selectDatas:self listInfo:_quizList completion:^(DataSelectModel *seleced) {
        _selectedQuiz = seleced;
        _txtQuizSelect.text = _selectedQuiz.title;
        [self updateUI];
        
    }];
}

- (void)requestQuizUpdate{
    QuizModel *quizInfo = (QuizModel *)_selectedQuiz.value;
    NSLog(@"Quiz Info : %@", quizInfo);
    
    NSString *quiz = quizInfo.quiz;
    if (quizInfo.isUserEditQuiz) {
        quiz = [_txtSelfQuiz.text trim];
    }
    
    //parameters
    NSDictionary *parameter = @{@"type": @"quiz" ,
                                @"quiz": quiz,
                                @"quiz_id":quizInfo.quizId,
                                @"status_code":quizInfo.statusCode,
                                @"answer":answer};
    
    NSString *path = [[JDFacade facade] getUrlWithCustGroupIDAndMemberID:API_PUT_MEMBER_UPDATE];
    
    [[RequestHandler handler] sendAsyncPutRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {
        
        [JDFacade facade].loginUser.quiz = quiz;
        [self dismissViewControllerAnimated:YES completion:nil];
        [self.delegate dismissQuizView];
        
    } failure:^(id errorObject) {
        
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestInviteQuizList {
    if (![JDFacade facade].loginUser.hasHomeHub) {
        return;
    }
    
    
    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];
    }];
    
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if ([textField isEqual:_txtQuizSelect]) {
        [self showQuizList];
        return NO;
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    if (_txtSelfQuiz.text.length > 0) {

        UIImage *active = [ImageUtil stretchedImage:[UIImage imageNamed:@"img_input_round_bg_active"] expectSize:CGSizeMake(_txtSelfQuiz.frame.size.width, _txtSelfQuiz.frame.size.height)];
        [_txtSelfQuiz setBackground:active];
        _btnConfirm.enabled = YES;
    } else {
        _btnConfirm.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;
        }
    }
    
    return result;
}

- (IBAction)btnInputQuizTouched:(id)sender {
    if (_popDate == nil) {
        _popDate = [[CustomDatePopupView alloc] initWithTitle:@"정답 날짜 입력"];
    }
    
    [_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];
            } 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];
        }
    }];
}

- (IBAction)btnCancelTouched:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)btnConfirmTouched:(id)sender {
    [self requestQuizUpdate];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
