//
//  GroupModifyViewController.m
//  kneet
//
//  Created by Jason Lee on 4/30/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

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

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

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

#import "NewGroupPopupView.h"
#import "CustomTextField.h"

#define kfGroupTableViewCellHeight 100.0f

@implementation GroupModifyTableViewCell

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

@end
@interface GroupModifyViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSMutableArray<DeviceModel> *_deviceList;
     UIImage *_bgCellImage1, *_bgCellImage2;
}
@end


#pragma mark - Class Definition

@implementation GroupModifyViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}


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

    self.title = NSLocalizedString(@"그룹 편집",nil);
}

- (void)initUI {

    

    
    [self generateOptionButton];

    //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"]];

    [self setThingsPopoverOptions];
}

- (void)setThingsPopoverOptions {
    //set Popover Contents
    __weak typeof(self) weakSelf = self;
    _popooverOptionArray = [[NSMutableArray alloc] init];

    [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"그룹에 장치 추가",nil),
                                      @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(addDeviceToGroup)]}];

    [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"그룹 삭제",nil),
                                      @"iconName": @"tp_01_img_bg_morepopup_icon_del",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(deleteGroup)]}];
}

- (void)prepareViewDidLoad {
    //FIXME : 뮤터블을 사용할 이유가 있나?
    _deviceList = (NSMutableArray<DeviceModel> *)[NSMutableArray arrayWithArray:_group.devices];
    [_btnGroupName setTitle:_group.dvcgrpName forState:UIControlStateNormal];
    [_tableView reloadData];
}

#pragma mark - Main Logic


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

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

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

    GroupModifyTableViewCell *cell = (GroupModifyTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

    DeviceModel *device = _deviceList[indexPath.row];

    cell.lblTitle.text = device.deviceName;
    cell.btnDelete.value = device;
    [cell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] placeholderImage:nil];

    if (![cell.btnDelete actionsForTarget:self forControlEvent:UIControlEventTouchUpInside]) {
        [cell.btnDelete addTarget:self action:@selector(btnDeleteDeviceTouched:) forControlEvents:UIControlEventTouchUpInside];
    }

    //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];
}


- (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 - Main Logic

//그룹 삭제
- (void)requestDeleteGroup {
    //parameters
    NSString *path = [NSString stringWithFormat:API_DELETE_GROUP, _group.dvcgrpId];

    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:nil modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {

        [[JDFacade facade] toast:NSLocalizedString(@"그룹이 삭제되었습니다", @"그룹이 삭제되었습니다")];

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

        [self.navigationController popToRootViewControllerAnimated:YES];

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

- (void)requestDeleteDeviceAtGroup:(DeviceModel *)device {
    //parameters
    NSString *path = [NSString stringWithFormat:API_POST_GROUP_DELETE, _group.dvcgrpId];

    NSDictionary *parameter = @{@"device_id": device.deviceId};

    [[RequestHandler handler] sendAsyncRequestAPIPath:path method:ksHTTPRequestDELETE parameters:parameter modelClass:[JDJSONModel class] showLoadingView:YES completion:^(id responseObject) {

        [_deviceList removeObject:device];

        ThingsViewController *vc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
        [vc prepareViewDidLoad];

        [[JDFacade facade] toast:NSLocalizedString(@"삭제 되었습니다", @"삭제 되었습니다")];
        [_tableView reloadData];

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


#pragma mark - UI Events
- (void)addDeviceToGroup {

    //그룹에 장치 추가로 이동.
    ThingsGroupAddViewController *vc = (ThingsGroupAddViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsGroupAddViewController" storyboardName:@"Things"];
    vc.addedGroup = _group;

    ThingsViewController *tvc = [[JDFacade facade] viewControllerOnNaviationController:[ThingsViewController class]];
    vc.groupList = tvc.groupList;

    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
}

- (void)deleteGroup {

    [self dismissOptionPopOver:^{
        
        CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"그룹 삭제", @"그룹 삭제") message:NSLocalizedString(@"그룹을 삭제하시겠습니까?\n장치는 삭제되지 않고\n미분류 그룹으로 이동됩니다", @"그룹을 삭제하시겠습니까?\n장치는 삭제되지 않고\n미분류 그룹으로 이동됩니다") delegate:nil OKButtonTitle:NSLocalizedString(@"삭제", @"삭제") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
        [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {//삭제
                [self requestDeleteGroup];
            }
        }];
    }];

}

- (IBAction)btnGroupNameTouched:(id)sender {

    NewGroupPopupView *popupView = [[NewGroupPopupView alloc] initFromNib];
    popupView.group = _group;

    [popupView showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            [_btnGroupName setTitle:popupView.txtGroupName.text forState:UIControlStateNormal];
        }
    }];
}

- (void)setGroup:(GroupsModel *)group {
    _group = group;
}

- (void)btnDeleteDeviceTouched:(id)sender {
    CustomButton *btn = (CustomButton *)sender;
    DeviceModel *device = (DeviceModel *)btn.value;

    [self requestDeleteDeviceAtGroup:device];
}

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


@end
