//
//  MobilesOverViewController.m
//  kneet
//
//  Created by Jason Lee on 6/12/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//

#import "MobilesOverViewController.h"
#import "CustomLabel.h"
#import "CustomRadioGroup.h"
#import "JDObject.h"
#import "NewMobileViewController.h"
#import "CommonUtil.h"
#import "RequestHandler.h"
#import "CustomButton.h"

@implementation MobilesOverTitleViewCell

@end

@implementation MobilesOverTableViewCell

- (void)awakeFromNib {
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    self.backgroundColor = [UIColor clearColor];
}

@end

@interface MobilesOverViewController () <UITableViewDataSource, UITableViewDelegate> {

    BOOL _isNotFirstLoading;
    UIImage *_bgCellImage1, *_bgCellImage2;
    CustomRadioReusableGroup *_rgroup;

}
@end


#pragma mark - Class Definition

@implementation MobilesOverViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    // initialize
    _rgroup = [[CustomRadioReusableGroup alloc] init];
    _rgroup.tableView = _tableView;

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {
    

    //set tableview option
    _tableView.delegate = self;
    _tableView.dataSource = self;

    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];

    _tableView.tableFooterView = [[UIView alloc] init]; //this call table events;

    UIEdgeInsets insets = UIEdgeInsetsMake(4, 4, 4, 4);
    _bgCellImage1 = [CommonUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
    _bgCellImage2 = [CommonUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
    
    //Localization
    _lblActionInfo.text = NSLocalizedString(@"선택한 단말은 등록해제 됩니다.\n등록 해제할 단말이 홈규칙에서 위치센서로 사용되고 있나요? 이 경우, 단말을 등록해제하면 관련된 규칙이 중지됩니다. 중지된 규칙은 편집 후 다시 시작할 수 있습니다.", @"선택한 단말은 등록해제 됩니다.\n등록 해제할 단말이 홈규칙에서 위치센서로 사용되고 있나요? 이 경우, 단말을 등록해제하면 관련된 규칙이 중지됩니다. 중지된 규칙은 편집 후 다시 시작할 수 있습니다.");
    
    [_btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {

}

#pragma mark - Main Logic

- (void)requestReplaceMobile {

    MobileDeviceModel *mobile = _rgroup.valueForChecked;
    //parameters
    NSDictionary *parameter = @{@"email_id": [JDFacade facade].tmpEmailId,
                                @"password": [JDFacade facade].tmpPassword,
                                @"service_id": MOBILE_SERVICE_ID,
                                @"device_sn": [JDFacade facade].deviceUUID};

    NSString *path = [NSString stringWithFormat:API_POST_REPLACE_MOBILE_DEVICE];

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

        LoginModel *result = (LoginModel *) responseObject;

        if (result) {//API 성공 ,
            NewMobileViewController *vc = (NewMobileViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"NewMobileViewController" storyboardName:@"SignUp"];
            vc.checkedAutoLogin = _checkedAutoLogin;
            vc.replaceDeviceSn = mobile.deviceSn;
            vc.nickname = result.nickname;
            [[JDFacade facade] presentViewControllerByPush:vc pvc:self];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];

}

#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _mobileList.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 100.0f;
    if (indexPath.row == 0) {//title
        height = 121.0f;
    }
    return height;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = nil;

    if (indexPath.row == 0) {//title
        MobilesOverTitleViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        tcell.lblNotify.text = NSLocalizedString(@"등록 가능한 단말 수를 초과했습니다\n아래 단말 중 인증을 대체할 단말을 고르면\n현재 단말로 이용을 할 수 있습니다", @"등록 가능한 단말 수를 초과했습니다\n아래 단말 중 인증을 대체할 단말을 고르면\n현재 단말로 이용을 할 수 있습니다");
        
        cell = tcell;
    } else {
        MobilesOverTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

        if (tcell == nil) {
            tcell = [[MobilesOverTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CellIdentifier"];
        }

        MobileDeviceModel *mobile = _mobileList[indexPath.row - 1];
        tcell.lblMobileName.text = mobile.deviceName;
        tcell.lblCreateDate.text = mobile.createDatetime;

        tcell.rdoSelect.value = mobile;
        if (indexPath.row == 1 && !_isNotFirstLoading) {
            _isNotFirstLoading = YES;
            tcell.rdoSelect.checked = YES;
        } else {
            tcell.rdoSelect.checked = [tcell.rdoSelect getRadioStatusFromValue];
        }

        [_rgroup addRadioButton:tcell.rdoSelect];

        cell = tcell;
        //set background image
        if (indexPath.row % 2 == 1) {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage1];
        } else {
            cell.backgroundView = [[UIImageView alloc] initWithImage:_bgCellImage2];
        }
    }

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (indexPath.row == 0) //제목 셀인 경우, 리턴
        return;

    MobilesOverTableViewCell *tcell = (MobilesOverTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    [_rgroup someRadioButtonTouched:tcell.rdoSelect];

    [_tableView reloadData];
}


- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {

    // Remove seperator inset
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }

    // Prevent the cell from inheriting the Table View's margin settings
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        [cell setPreservesSuperviewLayoutMargins:NO];
    }

    // Explictly set your cell's layout margins
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}



#pragma mark - UI Events
- (IBAction)btnConfirmTouched:(id)sender {

    [self requestReplaceMobile];
}

- (IBAction)btnCancelTouched:(id)sender {
    [[JDFacade facade] dismissViewControllerByPush:self];
}


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


@end
