//
//  ThingsAddIncludeViewController.m
//  kneet2
//
//  Created by Jason Lee on 11/13/15.
//  Copyright © 2015 ntels. All rights reserved.
//

#import "JDObject.h"

#import "RequestHandler.h"
#import "DeviceModel.h"

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

#import "ThingsAddIncludeViewController.h"
#import "ThingsAddFailViewController.h"
#import "ThingsAddCompleteViewController.h"


@interface ThingsAddIncludeViewController () {
    NSTimer *_timer;
    NSInteger _elapsedSeconds;
}
@end


#pragma mark - Class Definition

@implementation ThingsAddIncludeViewController


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


- (void)initUI {
    _elapsedSeconds = 60;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        _maskView.alpha = 0.7;
    } completion:^(BOOL finished) {
        
        _constraintPopViewTop.constant = (IPHONE_HEIGHT - _popView.height) / 2;
        
        [UIView animateWithDuration:kfAnimationDur animations:^{
            [self.view layoutIfNeeded];
        }];
    }];
}

- (void)prepareViewDidLoad {
    
    if (_addableDevice) {
        _lblDesc.text = [NSString stringWithFormat:@"%@의\n00 버튼을\n00 누르세요", _addableDevice[@"deviceName"]];
        [self requestIncludeDevice];
    } else if (_removableDevice) {
        _lblDesc.text = [NSString stringWithFormat:@"%@의\n00 버튼을\n00 누르세요", _removableDevice.deviceName];
        [self requestExcludeDevice];
    }
}

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

    NSString *path = [NSString stringWithFormat:API_POST_DEVICE_INCLUSION, [JDFacade facade].loginUser.homehubDeviceId];
    
    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:nil modelClass:[DeviceModel class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DeviceModel *device = (DeviceModel *)responseObject;
        
        if (device) {//API 성공 ,
            [self requestCheckInclustion:device.commandId];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestExcludeDevice {
    NSString *path = [NSString stringWithFormat:API_DELETE_DEVICE_EXCLUSION, [JDFacade facade].loginUser.homehubDeviceId];
    
    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[DeviceModel class] showLoadingView:YES completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DeviceModel *device = (DeviceModel *)responseObject;
        
        if (device) {//API 성공 ,
            [self requestCheckInclustion:device.commandId];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)requestCheckInclustion:(NSString *)commandId {
    
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(updateInclusionStatus) userInfo:nil repeats:YES];
//        _timer = [NSTimer timerWithTimeInterval:1.0f
//                                                 target:self
//                                               selector:@selector(updateInclusionStatus)
//                                               userInfo:nil repeats:YES];
//        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
    }
    
    //parameters
    NSDictionary *parameter = @{@"command_id": commandId};
    NSString *path = [NSString stringWithFormat:API_GET_DEVICE_COMMAND, [JDFacade facade].loginUser.homehubDeviceId];
    
    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestGET parameters:parameter
                                           modelClass:[DeviceModel class] showLoadingView:NO completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        DeviceModel *device = (DeviceModel *)responseObject;
        
        if (device) {//API 성공 ,
            
            if ([device.status isEqualToString:KNEET_DEVICE_WAITING]) {
                if (_elapsedSeconds > 2) {
                    [self performSelector:@selector(requestCheckInclustion:) withObject:commandId afterDelay:3.0f];
                }
                //retry
                return;
                
            } else if ([device.status isEqualToString:KNEET_DEVICE_INCLUSION] || [device.status isEqualToString:KNEET_DEVICE_EXCLUSION]) {
                //success
                if (_timer) {
                    [_timer invalidate];
                    _timer = nil;
                }
                ThingsAddCompleteViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddCompleteViewController" storyboardName:@"Things"];
                vc.isDeleteMode = [device.status isEqualToString:KNEET_DEVICE_EXCLUSION];
                
                vc.providesPresentationContextTransitionStyle = YES;
                vc.definesPresentationContext = YES;
                
                [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
                
                [self presentViewController:vc animated:YES completion:nil];
            }
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage completionHander:^{
            [self didFailInclusion];
        }];
    }];

}

- (void)didFailInclusion {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    ThingsAddFailViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddFailViewController" storyboardName:@"Things"];
    
    vc.addableDevice = _addableDevice;
    
    vc.providesPresentationContextTransitionStyle = YES;
    vc.definesPresentationContext = YES;
    
    [vc setModalPresentationStyle:UIModalPresentationOverCurrentContext];
    
    UIViewController *pvc = self.presentingViewController;
    [self dismissViewControllerAnimated:NO completion:^{//TODO : UI Confirm with Mr.Mo
        [pvc presentViewController:vc animated:YES completion:nil];
    }];
}

- (void)updateInclusionStatus {
    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
        _lblElapsedTime.text = [NSString stringWithFormat:@"%zd", _elapsedSeconds];
        _elapsedSeconds--;
        
        if (_elapsedSeconds == 0) {
            [self didFailInclusion];
        }
    });
}


#pragma mark - UI Events
- (IBAction)btnCancelTouched:(id)sender {
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
    [UIView animateWithDuration:kfAnimationDur animations:^{
        _maskView.alpha = 0.0;
    } completion:^(BOOL finished) {
        [[JDFacade facade] dismissModalStack:NO completion:^{
            [[JDFacade facade] toast:@"취소되었습니다"];
        }];
    }];
}


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



@end