//
//  ExternHeatPopupView.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 "CustomTextField.h"

#import "WeatherLocationPopupView.h"

#import "ExternHeatPopupView.h"
#import "RequestHandler.h"
#import "TemperaturePopupView.h"
#import "TimePickerPopupView.h"

@interface ExternHeatPopupView () {
    CommonCode *_weatherLocation;
    NSArray<CommonCode> *_locations;
    NSString *_temperature;
    
    WeatherLocationPopupView *_cpopup;
    TemperaturePopupView *_tpopup;
    
    BOOL tempPlus;
}

@end

@implementation ExternHeatPopupView

- (id)initFromNib {

    for (UIView *view in [CommonUtil nibViews:@"ExternHeatPopupView"]) {
        if ([view isKindOfClass:[ExternHeatPopupView class]]) {
            self = (ExternHeatPopupView *)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];
//            }
            
            [_chkDays[0] setDaySelectBgImage:1];
            [_chkDays[6] setDaySelectBgImage:3];
            
            for (int i = 1; i < 6; i++) {
                [_chkDays[i] setDaySelectBgImage:2];
            }
            
            if (!_lblCity.touchHandler) {
                [_lblCity addTouchEventHandler:^(id label) {
                    [self lblCityTouched:label];
                }];
            }
            
            if (!_lblHeat.touchHandler) {
                [_lblHeat addTouchEventHandler:^(id label) {
                    [self lblHeatTouched:label];
                }];
            }
            
            [self.imgTitleBar setImage:[UIImage imageNamed:@"img_popup_bg_head"]inset:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnConfirm setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_right_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left"] forState:UIControlStateNormal capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            [self.btnCancel setBackgroundImage:[UIImage imageNamed:@"img_popup_btn_left_press"] forState:UIControlStateHighlighted capInsets:UIEdgeInsetsMake(kfTopInset,kfRightInset,kfBottomInset,kfLeftInset)];
            
            //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)setExternHeatTrigger:(ItemModel *)externHeatTrigger {
    _externHeatTrigger = externHeatTrigger;

    if (_externHeatTrigger.itemSubTypeCode && [_externHeatTrigger.itemSubTypeCode isEqualToString:ksItemSubTypeCodeHeat]) {//기존 데이터가 있을 경우,
        
        ItemSubModel *subItem = _externHeatTrigger.heats[0];
        
        _btnOver.selected = [subItem.conditionTypeCode isEqualToString:ksConditionTypeCodeGreatOrEqual];
        _btnBelow.selected = !_btnOver.selected;
        
        _temperature = subItem.cmdclsValue;
        
        _btnZeroDegree.selected = [_temperature containsString:@"-"];
        NSString *tempNumber = [_temperature stringByReplacingOccurrencesOfString:@"+" withString:@""];
        tempNumber = [tempNumber stringByReplacingOccurrencesOfString:@"-" withString:@""];
        
        _tfTemper.text = tempNumber;
        _lblHeat.text = [NSString stringWithFormat:@"%@℃ 보다", _temperature];
        [_lblHeat setUnderLine:[NSString stringWithFormat:@"%@℃", _temperature]];
        
        
        for (NSInteger i = 0 ; i < WEEKDAYS.count ; i++) {
            
            if ([subItem.dayofweek containsString: [WEEKDAYS objectAtIndex:i]]) {
                
                CustomCheckBox *chk = [_chkDays objectAtIndex:i];
                chk.checked = YES;
            }
        }
        
    } else {//is new
        
        _externHeatTrigger.itemName = @"더울때 / 추울때";
        _externHeatTrigger.itemSubTypeCode = ksItemSubTypeCodeHeat;
        
        _btnOver.selected = YES;
        _btnZeroDegree.selected = NO;
        _temperature = @"0";
        _lblHeat.text = @"0℃ 보다";
        [_lblHeat setUnderLine:@"0℃"];
        
//        for (CustomCheckBox *chk in _chkDays) {
//            chk.checked = YES;
//        }
    }
}

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


- (void)didMoveToSuperview {
    [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 = _externHeatTrigger.heats.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)changeTempPlusMinus:(id)sender {
    
    UIButton *btn = sender;
    btn.selected = !btn.selected;
    
}

- (IBAction)btnActionBelowOver:(id)sender {
    _btnBelow.selected = NO;
    _btnOver.selected = NO;
    ((CustomButton *)sender).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];
        }
    }];
}

- (void)lblHeatTouched:(id)sender {
    if (!_tpopup) {
        _tpopup = [[TemperaturePopupView alloc] initFromNib];
    }
    
    ItemSubModel *subItem = _externHeatTrigger.heats.firstObject;
    _tpopup.temperature = subItem && subItem.cmdclsValue ? subItem.cmdclsValue : nil;
    
    [_tpopup showWithCompletion:^(CustomAlertView *alertView, NSInteger buttonIndex) {
        if (buttonIndex == 0) {//OK
            _temperature = _tpopup.temperature;
            
            NSString *ftemp = [NSString stringWithFormat:@"%@℃", _temperature];
            _lblHeat.text = [NSString stringWithFormat:@"%@ 보다", ftemp];
            
            [_lblHeat setUnderLine:ftemp];
        }
    }];
}

- (IBAction)btnConfirmTouched:(id)sender {
    //validate
    if (![TimePickerPopupView validateCondition:_chkDays]) {
        return;
    }
    
    if (_tfTemper.text.trim.length == 0) {
        return;
    }

    ItemSubModel *subItem = nil;
    
    if (_externHeatTrigger.subItems && _externHeatTrigger.subItems.count) {
        subItem = _externHeatTrigger.subItems[0];
    }
    else {
        subItem = [[ItemSubModel alloc] init];
        
        _externHeatTrigger.heats = (NSMutableArray<ItemSubModel> *)[[NSMutableArray alloc] init];
        [_externHeatTrigger.heats addObject:subItem];
    }
    
    _temperature = [NSString stringWithFormat:@"%@%@",
                    _btnZeroDegree.selected ? @"-" : @"+",
                    _tfTemper.text];

    //externHeats
    subItem.sourceId = _weatherLocation.commonCode;
    subItem.sourceName = _weatherLocation.commonCodeName;
    subItem.conditionTypeCode = _btnOver.selected ? ksConditionTypeCodeGreatOrEqual : ksConditionTypeCodeLessOrEqual;
    subItem.cmdclsValue = _temperature;
    subItem.dayofweek = [TimePickerPopupView daysOfWeek:_chkDays];
    
    //set Days condition
    //[TimePickerPopupView setDaysCondition:_refConditions chkDays:_chkDays];
    
    [super btnConfirmTouched:sender];
}

@end
