

#import "MyAutocompleteView.h"


@interface MyAutocompleteView () <UITableViewDelegate, UITableViewDataSource>

@property(readwrite)MySuggestion* selectedSuggestion;
@property(readwrite) NSArray *suggestions;

@end

@implementation MyAutocompleteView
{
    BOOL _visible;

//    __weak UITextField *_queryTextField;
    UITextField *_queryTextField;
//    __weak UIViewController *_contextController;
    UIView* _parentView;

    UITableView *_table;
    MyAutocompleteItemsSource* _itemsSource;
    MyAutocompletionCellFactory* _cellFactory;
}

+ (MyAutocompleteView *)autocompleteViewBindedTo:(UITextField *)textField
                                     usingSource:(MyAutocompleteItemsSource*) itemsSource
                                     cellFactory:(MyAutocompletionCellFactory*) factory
//                                    presentingIn:(UIViewController *)controller
parentView:(UIView*) view
{
    return [[MyAutocompleteView alloc] initWithFrame:CGRectZero
                                           textField:textField
                                         itemsSource:itemsSource
                                         cellFactory:factory
//                                          controller:controller
                                          parentView:view];
}

- (id)initWithFrame:(CGRect)frame
          textField:(UITextField *)textField
        itemsSource:(MyAutocompleteItemsSource*) itemsSource
        cellFactory:(MyAutocompletionCellFactory*) factory
//         controller:(UIViewController *)controller
         parentView:(UIView*) view
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self loadDefaults];

        _queryTextField = textField;
        _itemsSource = itemsSource;
        _cellFactory = factory;
//        _contextController = controller;
        _parentView = view;

        _table = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _table.backgroundColor = [UIColor whiteColor];
        _table.separatorColor = self.separatorColor;
        _table.separatorStyle = self.separatorStyle;
        
        _table.delegate = self;
        _table.dataSource = self;

        [[NSNotificationCenter defaultCenter]
                               addObserver:self
                                  selector:@selector(queryChanged:)
                                      name:UITextFieldTextDidChangeNotification
                                    object:_queryTextField];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWasShown:)
                                                     name:UIKeyboardDidShowNotification
                                                   object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification
                                                   object:nil];

        [self addSubview:_table];
    }

    return self;
}

- (void)loadDefaults
{
    self.backgroundColor = [UIColor lightGrayColor];

    self.separatorColor = [UIColor lightGrayColor];
    self.separatorStyle = UITableViewCellSeparatorStyleSingleLine;// uitableviewcellsep UITableViewCellSeparatorStyleNone;

    self.topMargin = 0;
}

- (void)keyboardWasShown:(NSNotification *)notification
{
    NSDictionary *info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    CGFloat contextViewHeight = 0;
    CGFloat kbHeight = 0;
    if (UIInterfaceOrientationIsPortrait([UIApplication sharedApplication].statusBarOrientation))
    {
        contextViewHeight = _parentView.frame.size.height;//_contextController.view.frame.size.height;
        kbHeight = kbSize.height;
    }
    else if (UIInterfaceOrientationIsLandscape([UIApplication sharedApplication].statusBarOrientation))
    {
        contextViewHeight =_parentView.frame.size.width;// _contextController.view.frame.size.width;
        kbHeight = kbSize.width;
    }

    CGPoint textPosition = [_queryTextField convertPoint:_queryTextField.bounds.origin toView:_parentView]; //Taking in account Y position of queryTextField relatively to it's Window
    CGRect textfieldFrame = _queryTextField.frame;
    CGFloat calculatedY = textPosition.y + _queryTextField.frame.size.height + self.topMargin;
    CGFloat calculatedHeight = 130;//150;//contextViewHeight - calculatedY - kbHeight;

//    calculatedHeight += _contextController.tabBarController.tabBar.frame.size.height; //keyboard is shown over it, need to compensate

    self.frame = CGRectMake(_queryTextField.frame.origin.x,
                            calculatedY,
                            _queryTextField.frame.size.width,
                            calculatedHeight);
    _table.frame = CGRectMake(0+0.5, 0+0.5, self.frame.size.width-1, self.frame.size.height-1);
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    [self removeFromSuperview];
    _visible = NO;
}

- (void)queryChanged:(id)sender
{
    if ([_queryTextField.text length] >= _itemsSource.minimumCharactersToTrigger)
    {
        [_itemsSource itemsFor:_queryTextField.text whenReady:
                                                            ^(NSArray *suggestions)
                                                            {
                                                                if (_queryTextField.text.length
                                                                    < _itemsSource.minimumCharactersToTrigger)
                                                                {
                                                                    self.suggestions = nil;
                                                                    [_table reloadData];
                                                                }
                                                                else
                                                                {
                                                                    self.suggestions = suggestions;
                                                                    [_table reloadData];

                                                                    if (self.suggestions.count > 0 && !_visible)
                                                                    {
                                                                        [_parentView addSubview:self];
//                                                                        [_contextController.view addSubview:self];
                                                                        CGRect r= self.frame;
                                                                        _visible = YES;
                                                                    }
                                                                }
                                                            }];
    }
    else
    {
        self.suggestions = nil;
        [_table reloadData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.suggestions.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"TRAutocompleteCell";

    id cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil)
        cell = [_cellFactory createReusableCellWithIdentifier:identifier];

    NSAssert([cell isKindOfClass:[UITableViewCell class]], @"Cell must inherit from UITableViewCell");
//    NSAssert([cell conformsToProtocol:@protocol(TRAutocompletionCell)], @"Cell must conform TRAutocompletionCell");
   MyAutocompletionCell *completionCell = (MyAutocompletionCell *) cell;

    id suggestion = self.suggestions[(NSUInteger) indexPath.row];
//    NSAssert([suggestion conformsToProtocol:@protocol(TRSuggestionItem)], @"Suggestion item must conform TRSuggestionItem");
   MySuggestion* suggestionItem = (MySuggestion *) suggestion;

    [completionCell updateWith:suggestionItem];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    id suggestion = self.suggestions[(NSUInteger) indexPath.row];
   // NSAssert([suggestion conformsToProtocol:@protocol(TRSuggestionItem)], @"Suggestion item must conform TRSuggestionItem");

    self.selectedSuggestion = (MySuggestion *) suggestion;

    _queryTextField.text = self.selectedSuggestion.completionText;
    [_queryTextField resignFirstResponder];

    if (self.didAutocompleteWith)
        self.didAutocompleteWith(self.selectedSuggestion);
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]
                           removeObserver:self
                                     name:UITextFieldTextDidChangeNotification
                                   object:nil];
    [[NSNotificationCenter defaultCenter]
                           removeObserver:self
                                     name:UIKeyboardDidShowNotification
                                   object:nil];
    [[NSNotificationCenter defaultCenter]
                           removeObserver:self
                                     name:UIKeyboardWillHideNotification
                                   object:nil];
}

@end