//
//  MyAutocompleteItemsSource.m
//  testautocomplete
//
//  Created by Ray on 14-4-29.
//  Copyright (c) 2014年 United Software Applications, Inc. All rights reserved.
//

#import "MyAutocompleteItemsSource.h"
#import "MySuggestion.h"
@implementation MyAutocompleteItemsSource
{
    //    NSString *_apiKey;
    //    NSString *_language;
    NSUInteger _minimumCharactersToTrigger;
    
    BOOL _requestToReload;
    BOOL _loading;
}
- (id)initWithMinimumCharactersToTrigger:(NSUInteger)minimumCharactersToTrigger source:(NSArray*) predictions
//                                language:(NSString *)language
//                                  apiKey:(NSString *)apiKey
{
    self = [super init];
    if (self)
    {
        
        _minimumCharactersToTrigger = minimumCharactersToTrigger;
        self.predictions = predictions;
        //        _apiKey = apiKey;
        //        _language = language;
        
        //        self.location = kCLLocationCoordinate2DInvalid;
        //        self.radiusMeters = -1;
    }
    
    return self;
}

//- (id)initWithMinimumCharactersToTrigger:(NSUInteger)minimumCharactersToTrigger
//
//{
//    return [self initWithMinimumCharactersToTrigger:minimumCharactersToTrigger language:@"en" apiKey:apiKey];
//}
- (NSUInteger)minimumCharactersToTrigger
{
    return _minimumCharactersToTrigger;
}
- (void)itemsFor:(NSString *)query whenReady:(void (^)(NSArray *))suggestionsReady
{
    @synchronized (self)
    {
        if (_loading)
        {
            _requestToReload = YES;
            return;
        }
        
        _loading = YES;
        [self requestSuggestionsFor:query whenReady:suggestionsReady];
    }
}
-(void) put_predictions:(NSArray*)predictions
{
    self.predictions = predictions;
    
}
- (void)requestSuggestionsFor:(NSString *)query whenReady:(void (^)(NSArray *))suggestionsReady
{
    
    NSMutableArray *suggestions = [[NSMutableArray alloc] init];
//    NSArray *predictions =[[NSArray alloc] initWithObjects:@"aa",@"aab",@"bbc",@"bbbd",nil];
    
    for (int i=0;i<self.predictions.count;i++)
    {
        if([self.predictions[i] rangeOfString:query].location==0)
        {
            MySuggestion *suggestion = [[MySuggestion alloc] initWith:self.predictions[i]];
            [suggestions addObject:suggestion];
        }
    }
    
    if (suggestionsReady)
        suggestionsReady(suggestions);
    
    @synchronized (self)
    {
        _loading = NO;
        
        if (_requestToReload)
        {
            _requestToReload = NO;
            [self itemsFor:query whenReady:suggestionsReady];
        }
    }
    
}


@end
