//
//  InvitationAnswerViewController.m
//  kneet2
//
//  Created by Jason Lee on 10/21/15.
//  Copyright © 2015 ntels. All rights reserved.
//

#import "InvitationAnswerViewController.h"
#import "InvitationAnswerPopupView.h"
#import "RequestHandler.h"
#import "LoginModel.h"
#import "InvitationListViewController.h"
#import "UIImageView+WebCache.h"
#import "CustomImageView.h"
#import "ImageUtil.h"


@interface InvitationAnswerViewController () {
    InvitationAnswerPopupView *_apopup;
}
@end


#pragma mark - Class Definition

@implementation InvitationAnswerViewController


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


- (void)initUI {
    [_imgvFromProfile sd_setImageWithURL:[NSURL URLWithString:_invitation.imageFileName] placeholderImage:nil options:SDWebImageRefreshCached
     completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
         UIImage *maskImage = [ImageUtil resizeImage:[UIImage imageNamed:@"common_mask_circle"] width:90 height:90];
         UIImage *thumbImage = [ImageUtil getMaskedImageWithSourchImage:image andMaskImage:maskImage];
         
         _imgvFromProfile.image = thumbImage;
     }];
    
    _lblQuiz.text = _invitation.authorizationQuestion;
}

- (void)prepareViewDidLoad {
    
}

#pragma mark - Main Logic
- (void)requestJoinInvitation:(InvitationModel *)invitation {
    //parameters
    NSDictionary *parameter = @{@"homegrp_id": invitation.homegrpId,
                                @"authorization_reply": invitation.sdate,
                                @"status_code": ksYES};
    
    NSString *path = [NSString stringWithFormat:API_POST_HOMEGROUP_MEMBER_INVITATIONS];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[LoginModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        LoginModel *result = (LoginModel *) responseObject;
        
        if (result) {//API 성공 ,
            [JDFacade facade].loginUser.homegrpId = result.homegrpId; //초대에서 넘어오는 경우,
            
            UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"WelcomeViewController" storyboardName:@"Main"];
            [self presentViewController:vc animated:YES completion:nil];
            
        }
    } failure:^(id errorObject) {//답변이 틀린 경우,
        JDErrorModel *error = (JDErrorModel *)errorObject;
        
        if ([error.errorCode isEqualToString:@"400-102"]) {//답변이
            if ([error.errorCount integerValue] < 3) {//답변이 1,2회 틀린 경우,
                [[JDFacade facade] alert:error.errorMessage completionHander:^{
                    [self popInvitationAnswer:invitation];
                }];
            } else {//답변이 3회 틀린 경우,
                [[JDFacade facade] alert:error.errorMessage completionHander:^{
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                        InvitationListViewController *vc = (InvitationListViewController *)[JDFacade facade].currentViewController;
                        if ([vc isKindOfClass:[InvitationListViewController class]]) {
                            [vc requestInvitationList];
                        }
                    }];
                }];
            }
        } else {
            [[JDFacade facade] alert:error.errorMessage];
        }
    }];
}

- (void)popInvitationAnswer:(InvitationModel *)invitation {
    //pop
    if (!_apopup) {
        _apopup = [[InvitationAnswerPopupView alloc] initFromNib];
    }
    _apopup.invitation = invitation;
    [_apopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            invitation.sdate = _apopup.selectedDate;
            [self requestJoinInvitation:invitation];
        }
    }];
}
#pragma mark - UI Events
- (IBAction)btnAnswerTouched:(id)sender {
    [self popInvitationAnswer:_invitation];
}

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



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

@end