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

#import "CustomLabel.h"
#import "CustomImageView.h"
#import "CustomAlertView.h"
#import "CustomTextView.h"
#import "CustomButton.h"

#import "RulesDetailViewController.h"
#import "ScenesDetailViewController.h"
#import "ScenesRegisterViewController.h"
#import "RulesRegisterViewController.h"


@implementation SceneDetailActivationViewCell
- (void)awakeFromNib {
    _lblRunTitle.text = NSLocalizedString(@"지금 실행", @"지금 실행");
}

@end

@implementation ScenesDetailDisableViewCell

- (void)awakeFromNib {
    _lblDesc.text = NSLocalizedString(@"일부 장치가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요", @"일부 장치가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요");
}
@end

@interface ScenesDetailViewController () <UITableViewDataSource, UITableViewDelegate> {
    SceneDetailModel *_sceneDetail;

    NSInteger _actionCount;
    BOOL _isNotFirstLoading;
    UIImage *_iconAction;
    NSMutableArray *_arrayForHeader;
    UIImage *_runImageNormal, *_runImageDisable;
}
@end


#pragma mark - Class Definition

@implementation ScenesDetailViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}


- (void)initUI {

    
    

    _tableView.dataSource = self;
    _tableView.delegate = self;

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

    _tableView.tableFooterView = [[UIView alloc] init]; //this call table events;
    _iconAction = [UIImage imageNamed:@"tp_01_img_rule_rbox_icon_action"];

    if ([JDFacade facade].loginUser.level <= 10) {//심플멤버일 경우,
        _constraintActionTabHeight.constant = 0;
    }
    
    _runImageNormal = [UIImage imageNamed:@"tp_01_img_scene_btn_play"];
    _runImageDisable = [UIImage imageNamed:@"tp_01_img_scene_btn_play_disable"];
    
    [_btnEdit setTitle:NSLocalizedString(@"편집", @"편집") forState:UIControlStateNormal];
    [_btnDelete setTitle:NSLocalizedString(@"삭제", @"삭제") forState:UIControlStateNormal];
}

- (void)prepareViewDidLoad {

}

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

    self.title = NSLocalizedString(@"멀티 제어 상세",nil);
    //룰 상세 조회
    [self requestSceneDetail];
}

#pragma mark - Main Logic
- (void)requestSceneDetail {

    //parameters
    NSString *path = [NSString stringWithFormat:API_GET_SCENE_DETAIL_HOMEMODE, _scene.homegrpSceneId];

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

        _sceneDetail = (SceneDetailModel *) responseObject;

        if (_sceneDetail) {//API 성공 ,
            [self setSceneDetailContents];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)setSceneDetailContents {

    _actionCount = _sceneDetail.actions && _sceneDetail.actions.count ? _sceneDetail.actions.count : 0;
    [RulesDetailViewController cloneSubItemsForItemSubType:_sceneDetail.actions conditions:nil];

    [_tableView reloadData];
}

//씬 실행
- (void)requestExecuteScene {
    //parameters
    NSString *path = [NSString stringWithFormat:API_POST_SCENE_EXECUTE, _sceneDetail.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)requestDeleteScene {

    NSString *path = [NSString stringWithFormat:API_DELETE_SCENE, _sceneDetail.homegrpSceneId];

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

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

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

#pragma mark - UITableView DataSource & Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3 + ([_sceneDetail.deleteCnt boolValue] ? 1 : 0);
}

- (NSString *)titleForSectionHeader:(NSInteger)section {
    NSString *title = nil;
    switch (section) {
        case 1:
            title = NSLocalizedString(@"무엇을 실행할까요?", @"무엇을 실행할까요?");
            break;
    }
    return title;
}

- (UIImage *)imageForSection:(NSInteger)section {
    UIImage *image = nil;
    switch (section) {
        case 1:
            image = _iconAction;
            break;
    }
    return image;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIView *view = _arrayForHeader.count > section ? _arrayForHeader[section] : nil;
    if (!view) {
        RulesCreateHeaderTableViewCell *hcell = (RulesCreateHeaderTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"HeaderCellIdentifier"];
        CGFloat height = [self tableView:tableView heightForHeaderInSection:section];
        hcell.frame = CGRectMake(0, 0, IPHONE_WIDTH, height);

        if (section == 0) {//titleCell
            hcell.imgvTop.hidden = YES;
            hcell.constraintHeaderTitleTop.constant = 10;
        }

        view = [[UIView alloc] initWithFrame:hcell.frame];
        [view addSubview:hcell];
        hcell.lblHeaderTitle.text = [self titleForSectionHeader:section];

        [_arrayForHeader insertObject:view atIndex:section];
    }

    return view;
}

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

    if (section == 1) {
        return 72.0f;
    }
    return 0.01f;
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger count = 1;
    
    if (section == 1) {//actions
        count = _actionCount;
    }
    
    return count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    if (indexPath.section == 0) {//title
        height = 80;

    } else if (indexPath.section == 1) {//actions
        //calcualate subItemsText

        NSArray *items = _sceneDetail.actions;

        ItemModel *item = items[indexPath.row];
        CGFloat adjustHeight = [RulesRegisterViewController heightForSubItems:item isTrigger:NO];
        adjustHeight = adjustHeight > 0 ? adjustHeight + 15 + 20 : adjustHeight;

        height = 60 + adjustHeight;

    } else if (indexPath.section == 2) {//activation
        height = 90.0f;
    } else if (indexPath.section == 3) {//disable
        height = 52.0f;
    }

    return height;
}


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

    UITableViewCell *cell = nil;

    if (indexPath.section == 0) {//title
        RulesDetailTitleViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"TitleCellIdentifier"];

        if (tcell == nil) {
            tcell = [[RulesDetailTitleViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TitleCellIdentifier"];
        }
        tcell.lblRuleTitle.text = _sceneDetail.sceneName;
        tcell.lblRuleOwner.text = [NSString stringWithFormat:@"by %@", [JDFacade facade].loginUser.nickname];

        cell = tcell;

    } else if (indexPath.section == 2) {//activation
        SceneDetailActivationViewCell *tcell = [tableView dequeueReusableCellWithIdentifier:@"ActivationCellIdentifier"];

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

        //활성/비활성 이미지 적용
        UIImage *nimage = ![_sceneDetail.deleteCnt boolValue] ? _runImageNormal : _runImageDisable;
        [tcell.btnRun setImage:nimage forState:UIControlStateNormal];
        
        [tcell.btnRun addTarget:self action:@selector(btnRunSceneTouched:) forControlEvents:UIControlEventTouchUpInside];
        
        cell = tcell;

    } else if (indexPath.section == 3) {//disable
        cell = [tableView dequeueReusableCellWithIdentifier:@"DisableCellIdentifier"];
        
    } else {//actions

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

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

        NSArray *items = nil;
        if (indexPath.section == 1) {
            items = _sceneDetail.actions;
        }

        ItemModel *item = items[indexPath.row];
        [RulesRegisterViewController fillCell:tcell item:item isTrigger:NO];

        cell = tcell;
    }

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    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 - UI Events
- (void)btnRunSceneTouched:(id)sender {
    
    if ([_sceneDetail.deleteCnt boolValue]) {
        [[JDFacade facade] toast:NSLocalizedString(@"일부 장치가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요", @"일부 장치가 삭제되어 비활성 되었습니다\n편집 후 다시 사용해주세요")];
        return;
    }
    
    [self requestExecuteScene];
}

- (void)gotoModifyScene {
    ScenesRegisterViewController *vc = (ScenesRegisterViewController *)[CommonUtil instantiateViewControllerWithIdentifier:@"ScenesRegisterViewController" storyboardName:@"Scenes"];
    vc.tmpSceneDetail = _sceneDetail;
    
    vc.title = NSLocalizedString(@"멀티 제어 상세",nil);
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)btnEditTouched:(id)sender {
    
    if ([_sceneDetail.deleteCnt boolValue]) {//삭제된 장치가 있을 경우,
        
        NSMutableString *deletedDevices = [[NSMutableString alloc] init];
        for (ItemModel *item in _sceneDetail.actions) {
            if ([item.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDevice]) {//디바이스일 경우,
                for (PredefinedDeviceModel *pdevice in item.predDevices) {
                    if ([pdevice.deleteYn boolValue]) {//삭제된 장치를 추가
                        NSString *prefix = [deletedDevices isEmptyString] ? @"" : @", ";
                        [deletedDevices appendFormat:@"%@%@", prefix, pdevice.deviceName];
                    }
                }
            }
        }
        
        NSString *msg = [NSString stringWithFormat:NSLocalizedString(@"삭제된 장치를 정리 후 진행합니다\n\n%@", @"삭제된 장치를 정리 후 진행합니다\n\n%@"), deletedDevices];
        
        CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:msg delegate:nil OKButtonTitle:NSLocalizedString(@"확인", @"확인") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
        [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
            if (buttonIndex == 0) {//OK
                [self gotoModifyScene];                
            }
        }];
        return;
    }
    
    [self gotoModifyScene];
}

- (IBAction)btnDeleteTouched:(id)sender {
    NSString *messge = NSLocalizedString(@"삭제하시겠습니까?", @"삭제하시겠습니까?");

    CustomAlertView *alert = [[CustomAlertView alloc] initWithTitle:NSLocalizedString(@"알림", @"알림") message:messge delegate:self OKButtonTitle:NSLocalizedString(@"삭제", @"삭제") cancelButtonTitle:NSLocalizedString(@"취소", @"취소")];
    [alert showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            [self requestDeleteScene];
        }
    }];
}


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

@end
