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

#import "CustomButton.h"
#import "UIButton+WebCache.h"

#import "ThingsModifyViewController.h"

@interface ThingsDeviceIconCell () {

}
@property (weak, nonatomic) NSIndexPath *indexPath;
@end


@implementation ThingsDeviceIconCell

@end

@implementation ThingsDeviceHeaderView
- (void)awakeFromNib {
    _lblHeaderTitle.text = NSLocalizedString(@"아이콘 변경", @"아이콘 변경");
}

@end

@interface ThingsModifyViewController () <UICollectionViewDelegate, UICollectionViewDataSource> {

    NSArray<DeviceIconModel> *_iconList;
    CustomButton *_selectedDeviceIcon;
    BOOL _isNotFirstLoading;
}
@end

#pragma mark - Class Definition

@implementation ThingsModifyViewController


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

    [self initUI];
    [self prepareViewDidLoad];
}

- (void)initUI {

    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.scrollEnabled = NO;
    _collectionView.backgroundColor = kUIBgColor01;
    
    [_btnSave setTitle:NSLocalizedString(@"저장", @"저장") forState:UIControlStateNormal];
    [_btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
}

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

- (DeviceIconModel *)selectedIcon {
    return _selectedDeviceIcon ? _selectedDeviceIcon.value : nil;
}

#pragma mark - Main Logic
- (void)requestDeviceIcons {
    //parameters
    NSString *path = [NSString stringWithFormat:API_GET_DEVICE_ICONS, _device.deviceId];

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

        DeviceIconListModel *fetchedIconList = (DeviceIconListModel *) responseObject;

        if (fetchedIconList && fetchedIconList.list && fetchedIconList.list.count) {//API 성공 ,
            _iconList = fetchedIconList.list;

            NSInteger index = [_iconList indexOfObjectPassingTest:^BOOL(DeviceIconModel *obj, NSUInteger idx, BOOL *stop) {
                return [_device.imageFileName isEqualToString:obj.imageFileName];
            }];

            if (index != NSNotFound) {
                _selectedIcon = _iconList[index];
            }
            [_collectionView reloadData];
        }
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

#pragma mark - UICollectionView Delegate

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    NSInteger cellCount = _iconList.count; //+1은 추가관련
//    NSInteger adjustCount = (cellCount % 3) > 0;
//    CGFloat height = ((cellCount / 3) + adjustCount) * (64.0f + 15.0f); //한 로우에 4개씩 위치시킴,
//    _constraintCollectionViewHeight.constant = height;

    return cellCount;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *kCellID = @"CollectionCellIdentifier";
    ThingsDeviceIconCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellID forIndexPath:indexPath];


    DeviceIconModel *deviceIcon = _iconList[indexPath.row];

    cell.indexPath = indexPath;
    cell.btnDeviceIcon.value = deviceIcon;

    cell.btnDeviceIcon.imageEdgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    [cell.btnDeviceIcon.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [cell.btnDeviceIcon sd_setImageWithURL:[NSURL URLWithString:deviceIcon.imageFileName] forState:UIControlStateNormal];
    [cell.btnDeviceIcon addTarget:self action:@selector(btnDeviceIconTouched:) forControlEvents:UIControlEventTouchUpInside];

    if (!_isNotFirstLoading) {
        if ([_selectedIcon isEqual:deviceIcon]) {
            [self btnDeviceIconTouched:cell.btnDeviceIcon];
            _isNotFirstLoading = YES;
        }
    }

    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath
{

    ThingsDeviceHeaderView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:
                                   UICollectionElementKindSectionHeader withReuseIdentifier:@"HeaderView" forIndexPath:indexPath];

    return headerView;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    if (IPHONE_WIDTH == 414.0f) {//아이폰 6일 경우,
        return CGSizeMake(84.0f, 64.0f);

    } else if (IPHONE_WIDTH == 375.0f) {//아이폰 6+일경우
        return CGSizeMake(75.0f, 64.0f);
    }
    return CGSizeMake(64.0f, 64.0f);
}

- (IBAction)btnDeviceIconTouched:(id)sender {

    if (_selectedDeviceIcon) {
        [_selectedDeviceIcon faceOffImage];
    }

    CustomButton *btn = (CustomButton *)sender;
    _selectedDeviceIcon = btn;
    [btn faceOffImage];
}



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



@end
