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

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

#import "UIImageView+WebCache.h"
#import "CustomLabel.h"
#import "CustomImageView.h"
#import "CustomTextField.h"
#import "CustomButton.h"
#import "JYRefreshController.h"
#import "WYPopoverController.h"

#import "CommandClassControlView.h"
#import "ThingsDetailViewController.h"
#import "NewGroupPopupView.h"
#import "GroupModifyViewController.h"

#import "ThingsViewController.h"

#define kfThingsTableViewCellHeight 100.0f

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

@end

@interface ThingsHeaderTableViewCell () {
}

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

@implementation ThingsHeaderTableViewCell

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

- (void)btnEditTouched:(id)sender {
    GroupModifyViewController *vc = (GroupModifyViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"GroupModifyViewController" storyboardName:@"Things"];
    vc.group = _group;

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

@end

@implementation ThingsTableViewCell

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

@end

@implementation ThingsAddTableViewCell

- (void)awakeFromNib {
    _lblAdd.text = NSLocalizedString(@"내 장치를 등록해보세요", @"내 장치를 등록해보세요");
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
}

- (void)btnAddTouched:(id)sender {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddViewController" storyboardName:@"Things"];
    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
}

@end

@interface ThingsViewController () <UITableViewDelegate, UITableViewDataSource, ThingsHeaderTableViewCellDelegate> {

    UIImage *_bgCellImage1, *_bgCellImage2;
    NSMutableArray *_arrayForHeader;
    NSString *_deviceGroupId;
    UIImage *_offlineImage;
}

@property (strong, nonatomic) JYPullToRefreshController *refreshController;
@property (strong, nonatomic) JYPullToLoadMoreController *loadMoreController;

@end


#pragma mark - Class Definition

@implementation ThingsViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    _groupList = (NSMutableArray<GroupsModel> *)[[NSMutableArray alloc] init];

    [self initUI];
    [self prepareViewDidLoad];
}

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

    self.title = NSLocalizedString(@"내 장치", nil);
    [_tableView reloadData];
}

- (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];
    
    _offlineImage = [UIImage imageNamed:@"tp_01_img_things_offline_cover"];
}

- (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_refresh",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(refreshDeviceList)]}];

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

    [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새 그룹 추가",nil),
                                      @"iconName": @"tp_01_img_bg_morepopup_icon_groupadd",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(addNewGroup)]}];
}


- (void)prepareViewDidLoad {
    //fetch devices from server

    if (_groupList && _groupList.count) {
        [_groupList removeAllObjects];
        [_arrayForHeader removeAllObjects];
    }

    [self performSelector:@selector(requestDeviceList) withObject:nil afterDelay:0.0f];
}

- (void)updateDevice:(DeviceModel *)device {
    for (GroupsModel *group in _groupList) {
        for (DeviceModel *ldevice in group.devices) {
            if ([device.deviceId isEqualToString:ldevice.deviceId]) {
                ldevice.cmdclsValue = device.cmdclsValue;
                ldevice.contentValue = device.contentValue;
                break;
            }
        }
    }
}

- (void)addNewDevice {
    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddViewController" storyboardName:@"Things"];
    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
}

- (void)addNewGroup {
    [self dismissOptionPopOver:^{

        NewGroupPopupView *popupView = [[NewGroupPopupView alloc] initFromNib];
        [popupView showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {//OK
                NSLog(@"%@", popupView.txtGroupName.text);
            }
        }];
    }];
}

- (void)refreshDeviceList {
    [self performSelector:@selector(requestDeviceList) withObject:nil afterDelay:0.0f];
}

#pragma mark - Main Logic

- (void)requestDeviceList {

    //parameters
    NSDictionary *parameter = _deviceGroupId ?  @{@"dvcgrp_id": _deviceGroupId} : nil;

    NSString *path = [NSString stringWithFormat:API_GET_GROUPS_DEVICES];

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

        GroupsListModel *groupList = (GroupsListModel *)responseObject;

        if (groupList && groupList.groups && groupList.groups.count) {
            _groupList = (NSMutableArray<GroupsModel> *)[NSMutableArray arrayWithArray:groupList.groups];
            _arrayForHeader = [[NSMutableArray alloc] init]; //헤더 저장용으로 사용

            GroupModifyViewController *gvc = [[JDFacade facade] viewControllerOnNaviationController:[GroupModifyViewController class]];
            if (gvc) {
                for (GroupsModel *group in _groupList) {
                    if ([gvc.group.dvcgrpId isEqualToString:group.dvcgrpId]) {//동일 그룹이면 업데이트 해줌
                        gvc.group = group;
                        [gvc prepareViewDidLoad];
                        break;
                    }
                }
            }

        } else {
            if (!_groupList.count) {//이미 로드된 데이터가 있을 경우는 출력하지 않음.
//                    NoContentView *noContentView = [NoContentView viewFromNib];
//                    _tableView.tableFooterView = noContentView;
            }
        }

        [_tableView reloadData];

    } failure:^(id errorObject) {
//        [self.tableView.pullToRefreshView stopAnimating];

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

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

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

    if (!_groupList.count) {
        return nil;
    }
    GroupsModel *group = _groupList[section];

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

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

        hcell.delegate = self;
        hcell.section = section;
        hcell.group = group;
        hcell.btnEdit.hidden = [group.defaultYn boolValue];

        NSString *headerTitle = [NSString stringWithFormat:@"%@ (%@)", group.dvcgrpName, group.deviceCount];
        [hcell.btnHeader setTitle:headerTitle forState:UIControlStateNormal];

        if (_arrayForHeader.count == section) {
            [_arrayForHeader insertObject:view atIndex:section];
        }
    } else {
        ThingsHeaderTableViewCell *hcell = (ThingsHeaderTableViewCell *)view.subviews[0];
        NSString *headerTitle = [NSString stringWithFormat:@"%@ (%@)", group.dvcgrpName, group.deviceCount];
        [hcell.btnHeader setTitle:headerTitle forState:UIControlStateNormal];
    }

    return view;
}


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

    if (section == _groupList.count) {
        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 == _groupList.count) {//마지막 섹션에 장치 추가를 넣어줌
        return 1;
    }

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

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

    return group.devices.count;
}

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

    if (indexPath.section == _groupList.count) {
        height = _groupList.count ? 190.0f : IPHONE_HEIGHT - kfNavigationBarHeight;
        _tableView.scrollEnabled = _groupList.count;
    }

    return height;
}

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

    UITableViewCell *cell = nil;

    if (indexPath.section < _groupList.count) {
        GroupsModel *group = _groupList[indexPath.section];
        NSArray<DeviceModel> *deviceList = group.devices;

        ThingsTableViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

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

        tcell.lblTitle.textColor = [UIColor whiteColor];

        //뷰를 초기화함.
        [[tcell.controlContainerView subviews] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            UIView *subview = (UIView *)obj;
            [subview removeFromSuperview];
        }];

        DeviceModel *device = deviceList[indexPath.row];

        tcell.lblTitle.text = device.deviceName;

        //On-offline 처리
        [tcell.imgvIcon sd_setImageWithURL:[NSURL URLWithString:device.imageFileName] placeholderImage:nil];
        if (device.networkYn && ![device.networkYn isEqualToString:@"none"] && ![device.networkYn boolValue]) {
            
            if (!tcell.imgvIcon.subviews.count) {
                UIImageView *imgvOffline = [[UIImageView alloc] initWithImage:_offlineImage];
                CGRect ir = tcell.imgvIcon.frame;
                ir.origin = (CGPoint){.x=0, .y=0};
                imgvOffline.frame = ir;
                [tcell.imgvIcon addSubview:imgvOffline];
            } else {
                [tcell.imgvIcon bringSubviewToFront:tcell.imgvIcon.subviews.firstObject];
            }
            
        } else {
            if (tcell.imgvIcon.subviews.count) {
                [tcell.imgvIcon.subviews.firstObject removeFromSuperview];
            }
        }

        CommandClassControlView *controlView = [CommandClassControlView viewForCommandClass:device.cmdclsType];
        controlView.device = device;

        tcell.controlContainerView.hidden = !controlView;
        if (!tcell.controlContainerView.hidden) {
            UIView *superview = tcell.controlContainerView;
            [superview addSubview:controlView];

            [controlView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(superview.mas_top);
                make.left.equalTo(superview.mas_left);
                make.center.equalTo(superview);
            }];
        }
        cell = tcell;

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

    } else {
        ThingsAddTableViewCell *acell = [tableView dequeueReusableCellWithIdentifier:@"AddCellIdentifier"];

        if (acell == nil) {
            acell = [[ThingsAddTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"AddCellIdentifier"];
        }
        cell = acell;
    }

    return cell;
}

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

    if (indexPath.section == _groupList.count) {
        UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ThingsAddViewController" storyboardName:@"Things"];
        [self.navigationController pushViewController:vc animated:YES];
        return;
    }


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

    ThingsDetailViewController *vc = (ThingsDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ThingsDetailViewController" storyboardName:@"Things"];

    vc.title = device.deviceName;
    vc.device = device;

    [self presentViewController:vc animated:YES completion:nil];
}

- (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 {

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

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

//    if (isExpanded) {
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:hcell.section] withRowAnimation:UITableViewRowAnimationFade];
//    } else {
//        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:hcell.section] withRowAnimation:UITableViewRowAnimationFade];
//    }
    [_tableView reloadData];
}

#pragma mark - UI Events



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

@end
