//
//  ThingsGroupAddViewController.h
//  kneet
//
//  Created by Jason Lee on 5/14/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
@import ObjectiveC.runtime;

#import "JDObject.h"
#import "RequestHandler.h"
#import "JDJSONModel.h"

#import "UIImageView+WebCache.h"
#import "CustomLabel.h"
#import "CustomImageView.h"
#import "CustomButton.h"
#import "CustomCheckBox.h"

#import "ThingsGroupAddViewController.h"
#import "ThingsViewController.h"
#import "GroupModifyViewController.h"
#import "ImageUtil.h"

#define kfThingsTableViewCellHeight 100.0f

@protocol ThingsGroupHeaderTableViewCellDelegate <NSObject>
@optional
- (void)didThingsHeaderTableViewCellBtnHeaderTouched:(id)sender;

@end

@interface ThingsGroupHeaderTableViewCell () {
}

@property (assign, nonatomic) id <ThingsGroupHeaderTableViewCellDelegate> delegate;
@end

@implementation ThingsGroupHeaderTableViewCell

- (IBAction)btnHeaderTouched:(id)sender {
    [_btnHeader faceOffImage];
    _group.unfold = !_group.unfold;
//    _group[@"expanded"] = [NSNumber numberWithBool:![_group[@"expanded"] boolValue]];

    if ([self.delegate respondsToSelector:@selector(didThingsHeaderTableViewCellBtnHeaderTouched:)]) {
        [self.delegate didThingsHeaderTableViewCellBtnHeaderTouched:self];
    }
}

@end

@implementation ThingsGroupTableViewCell

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

@end

@implementation ThingsGroupTitleTableViewCell

- (void)awakeFromNib {
    
    _lblGroupTitle.text = [NSString stringWithFormat:NSLocalizedString(@"추가할 그룹 : %@", @"추가할 그룹 : %@"), ksEmptyString];
    _lblGroupInfo.text = NSLocalizedString(@"다른 그룹에 속해있는 장치를 이 그룹에\n추가하면 해당 그룹에서 제외됩니다", @"다른 그룹에 속해있는 장치를 이 그룹에\n추가하면 해당 그룹에서 제외됩니다");
}

@end



@interface ThingsGroupAddViewController () <UITableViewDelegate, UITableViewDataSource, ThingsGroupHeaderTableViewCellDelegate> {

    UIImage *_bgCellImage1, *_bgCellImage2;
    NSMutableArray *_arrayForHeader;
    NSString *_deviceGroupId;
}
@end


#pragma mark - Class Definition

@implementation ThingsGroupAddViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    _deviceGroupId = ksEmptyString;

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];

    self.title = NSLocalizedString(@"그룹에 장치 추가",nil);
}

- (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 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_02"]];
    _bgCellImage2 = [ImageUtil resizableImageWithCapInsets:insets resizingMode:UIImageResizingModeStretch img:[UIImage imageNamed:@"tp_01_img_list_bg_01"]];
    
    //Localization
    [_btnSave setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}


- (void)prepareViewDidLoad {

}


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

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    }

    if (!_groupList.count) {
        return nil;
    }

    GroupsModel *group = _groupList[section-1];

    UIView *view = _arrayForHeader.count > section-1 ? _arrayForHeader[section-1] : nil;
    if (!view) {
        ThingsGroupHeaderTableViewCell *hcell = (ThingsGroupHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];

        view = [[UIView alloc] initWithFrame:hcell.contentView.frame];
        [view addSubview:hcell];

        hcell.delegate = self;
        hcell.section = section;
        hcell.group = group;
        [hcell.btnHeader setTitle:group.dvcgrpName forState:UIControlStateNormal];

        [_arrayForHeader insertObject:view atIndex:section-1];
    }

    return view;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    if (section == 0) {
        return 0.01f;
    }
    return 40.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01f;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if (section == 0) {//첫 섹션에 타이틀셀을 추가로 넣어줌
        return 1;
    }

    if (!_groupList.count) {
        return 0;
    }

    GroupsModel *group = _groupList[section-1];
    if (group.unfold) {
        return 0;
    }

    return group.devices.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = kfThingsTableViewCellHeight;

    if (indexPath.section == 0) {
        return 97.0f;
    }
    _tableView.scrollEnabled = _groupList.count;
    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {//title cell
        ThingsGroupTitleTableViewCell *tcell = (ThingsGroupTitleTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];
        tcell.lblGroupTitle.text = [NSString stringWithFormat:NSLocalizedString(@"추가할 그룹 : %@", @"추가할 그룹 : %@"), _addedGroup.dvcgrpName];
        cell = tcell;

    } else {

        ThingsGroupTableViewCell *tcell = (ThingsGroupTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

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

        GroupsModel *group = _groupList[indexPath.section-1];
        NSArray<DeviceModel> *deviceList = group.devices;
        DeviceModel *device = deviceList[indexPath.row];

        //set contents
        tcell.lblTitle.text = device.deviceName;

        [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] placeholderImage:nil];

        tcell.chkSelect.value = device;
        tcell.chkSelect.checked = [tcell.chkSelect getCheckStatusFromValue];

        cell = tcell;

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

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

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

    if (indexPath.section == 0) {
        return;
    }

    GroupsModel *group = _groupList[indexPath.section-1];
    NSArray<DeviceModel> *deviceList = group.devices;

    ThingsGroupTableViewCell *tcell = (ThingsGroupTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    tcell.chkSelect.value = deviceList[indexPath.row];
    tcell.chkSelect.checked = !tcell.chkSelect.checked;

    [_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 - ThingsHeaderTableViewCellDelegate
- (void)didThingsHeaderTableViewCellBtnHeaderTouched:(id)sender {

    ThingsGroupHeaderTableViewCell *hcell = (ThingsGroupHeaderTableViewCell *)sender;
    BOOL isExpanded = !hcell.group.unfold;

    [_tableView enumarateTableViewCellsSection:hcell.section UsingBlock:^(UITableViewCell *cell) {
        ThingsGroupHeaderTableViewCell *tmpCell = (ThingsGroupHeaderTableViewCell *)cell;
        tmpCell.contentView.hidden = isExpanded;
    }];

    [_tableView reloadData];
}

#pragma mark - Main Logic
- (void)requestAddDeviceToAddedGroup:(NSMutableArray *)devices {
    //parameters
    NSDictionary *parameter = @{@"devices": devices};

    NSString *path = [NSString stringWithFormat:API_POST_GROUP_ADD, _addedGroup.dvcgrpId];

    [[RequestHandler handler] sendAsyncPostRequestAPIPath:path parameters:parameter modelClass:[JDJSONModel class] completion:^(id responseObject) {

        [[JDFacade facade] toast:NSLocalizedString(@"장치가 추가되었습니다", @"장치가 추가되었습니다")];

        //리스트를 다시 로드함.
        ThingsViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
        [vc prepareViewDidLoad];

        [self.navigationController popViewControllerAnimated:YES];


    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];

}

#pragma mark - UI Events
- (void)btnBackTouched:(id)sender {
    //그룹 리스트로 리턴
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (IBAction)btnSaveTouched:(id)sender
{

    NSMutableArray *selectedDevices = [[NSMutableArray alloc] init];
    for (GroupsModel *group in _groupList) {
        for (DeviceModel *device in group.devices) {
            if ([[[JDFacade facade] getCheckBoxStatus:device] boolValue]) {
                [selectedDevices addObject:@{@"device_id" : device.deviceId}];
            }
        }
    }

    if (!selectedDevices.count) {
        [[JDFacade facade] alert:NSLocalizedString(@"선택된 장치가 없습니다\n장치를 선택해주세요", @"선택된 장치가 없습니다\n장치를 선택해주세요")];
        return;
    }

    [self requestAddDeviceToAddedGroup:selectedDevices];
}

- (IBAction)btnCancelTouched:(id)sender
{
    //리스트를 다시 로드함.
    ThingsViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
    [vc prepareViewDidLoad];

    [self.navigationController popViewControllerAnimated:YES];

    [self btnBackTouched:nil];
}


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

@end
