//
//  DaylightPopupView.m
//  kneet2
//
//  Created by Jason Lee on 11/24/15.
//  Copyright (c) 2015 ntels. All rights reserved.
//
#import "JDObject.h"

#import "ItemModel.h"
#import "JDJSONModel.h"

#import "CustomLabel.h"
#import "CustomButton.h"
#import "CustomCheckBox.h"
#import "CommonUtil.h"

#import "WeatherLocationPopupView.h"

#import "DaylightPopupView.h"
#import "RequestHandler.h"
#import "TimePickerPopupView.h"

@interface DaylightPopupView () {
    CommonCode *_weatherLocation;
    NSArray<CommonCode> *_locations;
    
    WeatherLocationPopupView *_cpopup;
}

@end

@implementation DaylightPopupView

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"DaylightPopupView"]) {
        if ([view isKindOfClass:[DaylightPopupView class]]) {
            self = (DaylightPopupView *)view;

            ((CustomCheckBox *)_chkDays[0]).value = ksDayOfWeekMON;
            ((CustomCheckBox *)_chkDays[1]).value = ksDayOfWeekTUE;
            ((CustomCheckBox *)_chkDays[2]).value = ksDayOfWeekWED;
            ((CustomCheckBox *)_chkDays[3]).value = ksDayOfWeekTHU;
            ((CustomCheckBox *)_chkDays[4]).value = ksDayOfWeekFRI;
            ((CustomCheckBox *)_chkDays[5]).value = ksDayOfWeekSAT;
            ((CustomCheckBox *)_chkDays[6]).value = ksDayOfWeekSUN;
            
            
            for (CustomCheckBox *chk in _chkDays) {
                [self alignTextAndImageOfButton:chk];
            }
            
            if (!_lblCity.touchHandler) {
                [_lblCity addTouchEventHandler:^(id label) {
                    [self lblCityTouched:label];
                }];
            }
            
            //Localization
            [self.btnConfirm setTitle:NSLocalizedString(@"확인", @"확인") forState:UIControlStateNormal];
            [self.btnCancel setTitle:NSLocalizedString(@"취소", @"취소") forState:UIControlStateNormal];
        }
    }

    return self;
}


- (void)alignTextAndImageOfButton:(UIButton *)button {
    // the space between the image and text
    CGFloat spacing = 6.0;
    float textMargin = 0;
    
    // get the size of the elements here for readability
    CGSize  imageSize   = button.imageView.image.size;
    CGSize  titleSize   = button.titleLabel.frame.size;
    CGFloat totalHeight = (imageSize.height + titleSize.height + spacing);      // get the height they will take up as a unit
    
    // lower the text and push it left to center it
    button.titleEdgeInsets = UIEdgeInsetsMake( 0.0, -imageSize.width +textMargin, - (totalHeight - titleSize.height), +textMargin );   // top, left, bottom, right
    
    // the text width might have changed (in case it was shortened before due to
    // lack of space and isn't anymore now), so we get the frame size again
    titleSize = button.titleLabel.bounds.size;
    
    button.imageEdgeInsets = UIEdgeInsetsMake(25, 0.0, 0.0, -titleSize.width );     // top, left, bottom, right
}


- (void)setDaylightTrigger:(ItemModel *)daylightTrigger {
    _daylightTrigger = daylightTrigger;
    
    if (_daylightTrigger.itemSubTypeCode && [_daylightTrigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeDaylight]) {//기존 데이터가 있을 경우,
        ItemSubModel *subItem = _daylightTrigger.daylights[0];
        
        _btnSunRise.selected = [subItem.sourceSubId isEqualToString:@"sunriseUtcTime"];
        _btnSunSet.selected = !_btnSunRise.selected;
        
    } else {//is new
        
        _daylightTrigger.itemName = @"해뜰때 / 질때";
        _daylightTrigger.itemSubTypeCode = ksItemSubTypeCodeDaylight;
        
        _btnSunRise.selected = YES;
        
        for (CustomCheckBox *chk in _chkDays) {
            chk.checked = YES;
        }
    }
}

- (void)setRefConditions:(NSMutableArray<ItemModel> *)refConditions {
    _refConditions = refConditions;
    
    [TimePickerPopupView setRefConditions:_refConditions chkDays:_chkDays];
}


- (void)didMoveToSuperview {
    if (self.superview) {
        [self requestLocationCode];
    }
}

#pragma mark - Main Logic

- (void)requestLocationCode {
    
    NSString *path = [NSString stringWithFormat:API_GET_LOCATION_CODES];
    
    [[RequestHandler handler] sendAsyncGetRequestAPIPath:path parameters:nil modelClass:[CommonCodeList class] completion:^(id responseObject) {
        if (!responseObject) {//응답결과가 잘못되었거나 없을 경우,
            return;
        }
        
        CommonCodeList *result = (CommonCodeList *) responseObject;
        
        if (result) {//API 성공 ,
            _locations = result.list;
            
            [self setDefaultLocation];
        }
        
    } failure:^(id errorObject) {
        JDErrorModel *error = (JDErrorModel *)errorObject;
        [[JDFacade facade] alert:error.errorMessage];
    }];
}

- (void)setDefaultLocation {
    
    ItemSubModel *subItem = _daylightTrigger.daylights.firstObject;
    NSString *location = subItem && subItem.sourceName ? subItem.sourceName : @"서울";
    
    for (CommonCode *code in _locations) {
        if ([code.commonCodeName isEqualToString:location]) {
            _weatherLocation = code;
            [[JDFacade facade] setRadioButtonStatus:@YES object:code];
            
            _lblCity.text = [NSString stringWithFormat:@"%@ 지역에", _weatherLocation.commonCodeName];
            [_lblCity setUnderLine:_weatherLocation.commonCodeName];
            break;
        }
    }
}


#pragma mark - UI Events

- (IBAction)btnSunRiseTouched:(id)sender {
    _btnSunRise.selected = YES;
    _btnSunSet.selected = NO;
}

- (IBAction)btnSunSetTouched:(id)sender {
    _btnSunRise.selected = NO;
    _btnSunSet.selected = YES;
}

- (void)lblCityTouched:(id)sender {
    
    if (!_cpopup) {
        _cpopup = [[WeatherLocationPopupView alloc] initFromNib];
        _cpopup.locations = _locations;
    }
    
    [_cpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {
            _weatherLocation = _cpopup.weatherLocation ? _cpopup.weatherLocation : _weatherLocation;
            
            _lblCity.text = [NSString stringWithFormat:@"%@ 지역에", _weatherLocation.commonCodeName];
            [_lblCity setUnderLine:_weatherLocation.commonCodeName];
        }
    }];
}

- (IBAction)btnConfirmTouched:(id)sender {
    //validate
    if (![TimePickerPopupView validateCondition:_chkDays]) {
        return;
    }

    ItemSubModel *subItem = nil;
    if (_daylightTrigger.subItems && _daylightTrigger.subItems.count) {
        subItem = _daylightTrigger.subItems[0];
    } else {
        subItem = [[ItemSubModel alloc] init];
        
        _daylightTrigger.daylights = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] init];
        [_daylightTrigger.daylights addObject:subItem];
    }


    //daylights
    subItem.sourceId = _weatherLocation.commonCode;
    subItem.sourceName = _weatherLocation.commonCodeName;
    subItem.sourceSubId = _btnSunRise.selected ? @"sunriseUtcTime" : @"sunsetUtcTime";

    //set Days condition
    [TimePickerPopupView setDaysCondition:_refConditions chkDays:_chkDays];
    
    [super btnConfirmTouched:sender];
}

@end
