//
//  VankeWeatherModel.m
//  vanke
//
//  Created by xiaomi on 15/10/4.
//  Copyright © 2015年 gomore. All rights reserved.
//

#import "VankeWeatherModel.h"
#import "VankeWeatherController.h"

@implementation DayWeather

@end

@implementation WeekWeather

+(Class) convertPropertyClassFor_weekData {
    return DayWeather.class;
}

@end

@interface VankeWeatherModel (private)

-(void) saveCache;
-(void) asyncSaveCache;

@end

@implementation VankeWeatherModel

-(void) removeAll {
    WeekWeather.DB.EMPTY();
    self.weather = nil;
}

-(void) loadOnline {
    [self sendMessage: VankeWeatherController.LOAD_WEATHER];
}

-(BOOL) loadCache: (NSString*) city {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDateStr = [dateFormatter stringFromDate:[NSDate date]];

    self.weather = [WeekWeather.DB.WHERE(@"city", city, @"date", currentDateStr).GET_RECORDS() lastObject];
    return _weather != nil;
}

-(void) saveCache {
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    [self performSelector:@selector(asyncSaveCache) withObject:nil afterDelay:0.1f];
}

-(void) asyncSaveCache {
    if (_weather == nil) {
        return;
    }
    
    // delete first
    WeekWeather.DB.WHERE(@"city", _weather.city, @"date", _weather.date).DELETE();
    
    // insert new
    _weather.SAVE();
}

-(void) handleMessage:(BeeMessage *)msg {
    [super handleMessage:msg];
}

ON_MESSAGE3(VankeWeatherController, LOAD_WEATHER, msg) {
    if (msg.succeed) {
        NSDictionary *dict = [msg.output dictAtPath:@"result"];
        if (dict) {
            WeekWeather *weekWeather = (WeekWeather*)[dict objectForClass:[WeekWeather class]];
            if ([weekWeather.weekData count] <= 0) {
                return;
            }
            
            DayWeather *weather = [weekWeather.weekData objectAtIndex:0];
            weather.city = weekWeather.city;
            weather.realTemperature = [self parseRealTemp: weather.date];
            weather.date = weekWeather.date;
            self.weather = weather;
            [self saveCache];
        }
    }
}

-(NSString*) parseRealTemp: (NSString*) src {
    NSRange range = [src rangeOfString:@"实时："];
    if (range.length <= 0) {
        return @"";
    } else {
        NSString *real = [src substringFromIndex:NSMaxRange(range)];
        range = [real rangeOfString:@")"];
        if (range.length > 0) {
            real = [real substringToIndex:NSMaxRange(range) - 1];
        }
        return [real stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    }
}

@end
