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

#import "UIImageView+WebCache.h"
#import "CustomLabel.h"
#import "CustomImageView.h"
#import "JYRefreshController.h"

#import "ScenesDetailViewController.h"
#import "ScenesViewController.h"
#import "CustomButton.h"
#import "ImageUtil.h"

#define kfScenesTableViewCellHeight 100.0f

@interface ScenesTableViewCell () {

}

@end
@implementation ScenesTableViewCell

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

}

@end

@implementation ScenesAddTableViewCell

- (void)awakeFromNib {
    self.backgroundColor = [UIColor clearColor];
    self.selectionStyle = UITableViewCellSelectionStyleNone;
    
    _lblActionDesc.text = NSLocalizedString(@"버튼 하나로 여러 장치가 동작되도록\n지금 바로 만들어보세요", @"버튼 하나로 여러 장치가 동작되도록\n지금 바로 만들어보세요");
}

- (void)btnAddTouched:(id)sender {

    UIViewController *vc = [CommonUtil instantiateViewControllerWithIdentifier:@"ScenesRegisterTypeViewController" storyboardName:@"Scenes"];
    [[JDFacade facade].currentViewController.navigationController pushViewController:vc animated:YES];
}

@end

@interface ScenesViewController () <UITableViewDataSource, UITableViewDelegate> {
    NSString *_pagingType, *_pagingId;
    NSMutableArray<SceneModel> *_sceneList;
    UIImage *_bgCellImage1, *_bgCellImage2;
    UIImage *_runImageNormal, *_runImageDisable;
}

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

@end


#pragma mark - Class Definition

@implementation ScenesViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    _sceneList = (NSMutableArray<SceneModel> *)[[NSMutableArray alloc] init];

    [self initUI];
    [self prepareViewDidLoad];
}

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

    self.title = NSLocalizedString(@"멀티 제어",nil);
}

- (void)initUI {

    

    
    [self generateOptionButton];

    //intialize tableview
    _tableView.dataSource = self;
    _tableView.delegate = self;

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

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

    //set refresh controls
    __weak typeof(self) weakSelf = self;
    self.refreshController = [[JYPullToRefreshController alloc] initWithScrollView:self.tableView];
    self.refreshController.pullToRefreshHandleAction = ^{
        [weakSelf requestRuleListRecently];
    };
    
    self.loadMoreController = [[JYPullToLoadMoreController alloc] initWithScrollView:self.tableView];
    self.loadMoreController.pullToLoadMoreHandleAction = ^{
        [weakSelf requestRuleListOlder];
    };

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

    _runImageNormal = [UIImage imageNamed:@"tp_01_img_scene_btn_play"];
    _runImageDisable = [UIImage imageNamed:@"tp_01_img_scene_btn_play_disable"];
    
    [self setThingsPopoverOptions];
}

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

    [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새로 고침", @"새로 고침"),
                                      @"iconName": @"tp_01_img_bg_morepopup_icon_refresh",
                                      @"target": weakSelf,
                                      @"selector": [NSValue valueWithPointer:@selector(refreshRuleList)]}];

    if ([JDFacade facade].loginUser.level > 10) {//파워유저 이상일 경우,
        [_popooverOptionArray addObject:@{@"menuName" : NSLocalizedString(@"새 멀티 제어 추가", @"새 멀티 제어 추가"),
                                          @"iconName": @"tp_01_img_bg_morepopup_icon_group_deviceadd",
                                          @"target": weakSelf,
                                          @"selector": [NSValue valueWithPointer:@selector(addNewScene)]}];
    }
}

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

- (void)refreshRuleList {
    _pagingId = nil;
    _pagingType = nil;

    if (_sceneList && _sceneList.count) {
        [_sceneList removeAllObjects];
    }
    [self performSelector:@selector(requestScenes) withObject:nil afterDelay:0.0f];
}

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

#pragma mark - Main Logic

- (void)requestRuleListRecently {

    SceneModel *firstScene = [_sceneList firstObject];
    _pagingType = ksListPagingTypeUpward;
    _pagingId = firstScene.homegrpSceneId;

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

- (void)requestRuleListOlder {

    SceneModel *lastScene = [_sceneList lastObject];
    _pagingType = ksListPagingTypeDownward;
    _pagingId = lastScene.homegrpSceneId;

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

- (void)requestScenes {

    NSDictionary *parameter = @{@"homegrp_scene_id": _pagingId ? _pagingId : ksEmptyString,
                                @"paging_type": _pagingType ? _pagingType : ksEmptyString};

    NSString *path = [NSString stringWithFormat:API_GET_SCENE];

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

        SceneListModel *fetchedRuleList = (SceneListModel *)responseObject;

        if (fetchedRuleList && fetchedRuleList.list && fetchedRuleList.list.count) {//API 성공,
            [_sceneList addObjectsFromArray:fetchedRuleList.list];

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

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

- (void)requestRunHomeGroupScene:(SceneModel *)scene {

    NSString *path = [NSString stringWithFormat:API_POST_SCENE_EXECUTE, scene.homegrpSceneId];

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

        JDJSONModel *result = (JDJSONModel *) responseObject;

        if (result) {//API 성공 ,
            if (result.msg && ![result.msg isEmptyString]) {
                [[JDFacade facade] alert:result.msg];
            } else {
                [[JDFacade facade] toast:NSLocalizedString(@"실행되었습니다", @"실행되었습니다")];
            }
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}


- (void)updateScene:(SceneModel *)scene {
    for (SceneModel *tmpScene in _sceneList) {
        if ([scene.homegrpSceneId isEqualToString:tmpScene.homegrpSceneId]) {
            tmpScene.sceneName = scene.sceneName;
            tmpScene.deleteCnt = scene.deleteCnt;
            break;
        }
    }

    [_tableView reloadData];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _sceneList.count + ([JDFacade facade].loginUser.level > 10 ? 1 : 0);
}

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

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

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

    UITableViewCell *cell = nil;

    if (indexPath.row < _sceneList.count) {
        ScenesTableViewCell *rcell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];

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

        SceneModel *scene = _sceneList[indexPath.row];
        
        //활성/비활성 이미지 적용
        UIImage *nimage = ![scene.deleteCnt boolValue] ? _runImageNormal : _runImageDisable;
        [rcell.btnRun setImage:nimage forState:UIControlStateNormal];
        
        rcell.btnRun.value = indexPath;
        rcell.lblSceneName.text = scene.sceneName;
        rcell.lblSceneName.textColor = [UIColor whiteColor];

        [rcell.btnRun addTarget:self action:@selector(btnRunTouchedOnCell:) forControlEvents:UIControlEventTouchUpInside];

        cell = rcell;

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

    } else {//씬 추가 셀
        ScenesAddTableViewCell *acell = [tableView dequeueReusableCellWithIdentifier:@"AddCellIdentifier"];

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

    return cell;
}

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

    if (indexPath.row == _sceneList.count) {//add cell 일 경우, 리턴,
        return;
    }

    //goto scene details
    ScenesDetailViewController *vc = (ScenesDetailViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ScenesDetailViewController" storyboardName:@"Scenes"];
    vc.scene = _sceneList[indexPath.row];

    [self.navigationController pushViewController:vc 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 - UI Events
- (IBAction)btnRunTouchedOnCell:(id)sender {
    CustomButton *btn = (CustomButton *)sender;

    NSIndexPath *indexPath = (NSIndexPath *)btn.value;
    SceneModel *scene = _sceneList[indexPath.row];

    if ([scene.deleteCnt boolValue]) {
        [[JDFacade facade] toast:NSLocalizedString(@"일부 장치가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요", @"일부 장치가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요")];
        return;
    }
    
    [self requestRunHomeGroupScene:scene];
}

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

@end
