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

#import "VankeWeatherController.h"

#define WEATHER_SERVER_URL @"http://api.map.baidu.com/telematics/v3/weather"
#define BAIDU_AK @"442b5fb0a1dc4dcbbccd26975e180e29"

#pragma mark -

@implementation VankeWeatherController

DEF_MESSAGE( LOAD_WEATHER )

- (void) LOAD_WEATHER:(BeeMessage *)msg
{
    if ( msg.sending )
	{
        msg.HTTP_GET(WEATHER_SERVER_URL).PARAM(@"location", @"上海").PARAM(@"output", @"json").PARAM(@"ak", BAIDU_AK).TIMEOUT(30);
	}
	else if ( msg.succeed )
	{
        NSDictionary *rootData = [msg.response objectFromJSONData];
        if (nil == rootData) {
            [msg setLastError];
            return;
        }
        
        int error = [[rootData objectForKey:@"error"] integerValue];
        if (error != 0) {
            NSString *status = [rootData objectForKey:@"status"];
            [msg setLastError: error domain:@"" desc:status];
            return;
        }
        
        id cities = [rootData objectForKey:@"results"];
        if ([cities count] <= 0) {
            [msg setLastError: 1 domain:@"" desc:@"没有城市天气数据"];
            return;
        }
        id curCity = [cities objectAtIndex:0];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        [dict setObject:[rootData objectForKey:@"date"] forKey:@"date"];
        [dict setObject:[curCity objectForKey:@"currentCity"] forKey:@"city"];
        [dict setObject:[curCity objectForKey:@"weather_data"] forKey:@"weekData"];
        [msg output: @"result", dict, nil];
	}
}

@end
