//
//  VDTableViewForPopover.h
//  DropDownList
//
//  Created by Claus Richter on 4/21/14.
//  Copyright (c) 2014 Claus Richter. All rights reserved.
//

#import "VDTableViewForPopover.h"
#import "VDMultilineCell.h"
#import "VDLabelWithDropDown.h"

#define CELL_HEIGHT 85
#define SELECTED_COLOR [UIColor blueColor]

static NSString* reuseIdentifier = @"multiLineCell";

@interface VDTableViewForPopover () {
    NSIndexPath* defaultSelectionIdxPath_;
    VDMultilineCell* cellGhost_;
    NSIndexPath* cellChostIndexPath_;
    CGPoint cellChostInitialCenter_;
    UIView* tempViewForDragging_;
}

@end

@implementation VDTableViewForPopover

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.tableView registerNib:[UINib nibWithNibName:@"VDMultilineCell" bundle:nil] forCellReuseIdentifier:reuseIdentifier];
    self.tableView.allowsSelection = YES;
    
    [_linkedTextField addTarget:self action:@selector(textFieldValueChanged) forControlEvents:UIControlEventEditingChanged];
    
    if (!_fixedTable) {
        UIPanGestureRecognizer* panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
        [self.tableView addGestureRecognizer:panRecognizer];
        panRecognizer.delegate = self;
    }
}

- (void)setItems:(NSArray *)items {
    if ([_items containsObject:[self linkedFieldText]]) {
        int index = [_items indexOfObject:[self linkedFieldText]];
        defaultSelectionIdxPath_ = [NSIndexPath indexPathForRow:index inSection:0];
//        [self.tableView selectRowAtIndexPath:defaultSelectionIdxPath_ animated:NO scrollPosition:UITableViewScrollPositionMiddle];
    }
    _items = items;
    [self.tableView reloadData];
}

- (CGFloat)height {
    if (!_items.count) return 0;
    return [self cellHeight] * _items.count;
}

#pragma mark- Table View Data Source

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

#pragma  mark- Table View Delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self cellHeight];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    VDMultilineCell* cell = (VDMultilineCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.text = _items[indexPath.row];
    cell.font = [self linkedFieldFont];
    cell.defaultColor = [self linkedFieldTextColor];
    cell.selectedColor = SELECTED_COLOR;
    if (defaultSelectionIdxPath_ && defaultSelectionIdxPath_.row == indexPath.row) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        cell.selected = YES;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    VDMultilineCell* cell = (VDMultilineCell*)[tableView cellForRowAtIndexPath:indexPath];
    [self setLinkedFieldText:cell.text];
    if (defaultSelectionIdxPath_ && defaultSelectionIdxPath_.row != indexPath.row) {
        defaultSelectionIdxPath_ = nil;
    }
    [_linkedTextField resignFirstResponder];
    if (_linkedLabel) {
        [_linkedLabel dismissPopover];
    }
}

#pragma mark- UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)recognizer {
    if ([recognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        UIPanGestureRecognizer *panRecognizer = (UIPanGestureRecognizer *)recognizer;
        CGPoint velocity = [panRecognizer velocityInView:self.tableView];
        
        BOOL shouldBegin = ABS(velocity.x) > ABS(velocity.y); // Horizontal panning
        NSLog(@"Should Begin %d", shouldBegin);
        return shouldBegin;
        //return ABS(velocity.x) < ABS(velocity.y); // Vertical panning
    } else {
        return YES;
    }
}

#pragma mark- Actions

- (void)textFieldValueChanged {
    NSIndexPath* selectedIndex = [[self.tableView indexPathsForSelectedRows] firstObject];
    if (selectedIndex) {
        [self.tableView deselectRowAtIndexPath:selectedIndex animated:NO];
    }
    
    NSInteger index = -1;
    for (NSString* string in _items) {
        if ([string hasPrefix:[self linkedFieldText]]) {
            index = [_items indexOfObject:string];
            break;
        }
    }
    
    if (index != -1) {
        NSIndexPath* indexPath = [NSIndexPath indexPathForRow:index inSection:0];
        [self.tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
    }
}

- (IBAction)panAction:(UIPanGestureRecognizer *)sender {
    if (sender.state == UIGestureRecognizerStateBegan) {
        [self createCellGhostAtPoint:[sender locationInView:self.tableView]];
    } else if (sender.state == UIGestureRecognizerStateEnded || sender.state == UIGestureRecognizerStateFailed || sender.state == UIGestureRecognizerStateCancelled) {
        if (cellGhost_) {
            CGPoint translation = [sender translationInView:self.tableView];
            if (translation.x > cellGhost_.frame.size.width/2) {
                [self removeDraggedItem];
                [self destroyCellGhost];
            } else if (translation.x < -cellGhost_.frame.size.width/2) {
                [self removeDraggedItem];
                [self destroyCellGhost];
            } else {
                if (cellGhost_ ) {
                    [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveEaseIn animations:^{
                        cellGhost_.center = cellChostInitialCenter_;
                    } completion:^(BOOL finished) {
                        [self destroyCellGhost];
                    }];
                }
            }
        }
    } else {
        CGPoint translation = [sender translationInView:self.tableView];
        CGPoint newCenter = cellChostInitialCenter_;
        newCenter.x += translation.x;
        newCenter.y += translation.y;
        cellGhost_.center = newCenter;
    }
}

- (void)createCellGhostAtPoint:(CGPoint)point {
    NSLog(@"Creating ghost image");
    cellChostIndexPath_ = [self.tableView indexPathForRowAtPoint:point];
    VDMultilineCell* cell = (VDMultilineCell*)[self.tableView cellForRowAtIndexPath:cellChostIndexPath_];
    if (cell.text.length != 0) {
        cellGhost_ = [self.tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
        cellGhost_.bounds = cell.bounds;
        cellGhost_.layer.borderColor = [UIColor grayColor].CGColor;
        cellGhost_.layer.borderWidth = 1;
        cellGhost_.text = cell.text;
        cellGhost_.font = cell.font;
        cellGhost_.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.05];
        
        CGPoint center = [self.tableView.superview convertPoint:cell.center fromView:cell.superview];
        [self.tableView.superview addSubview:cellGhost_];
        self.tableView.superview.clipsToBounds = NO;
        cellGhost_.center = center;
        cellChostInitialCenter_ = cellGhost_.center;
    }
}

- (void)destroyCellGhost {
    [cellGhost_ removeFromSuperview];
    cellGhost_ = nil;
    cellChostIndexPath_ = nil;
}

- (void)removeDraggedItem {
    if (cellGhost_) {
        NSLog(@"Removing %@", cellGhost_.text);
        NSMutableArray* array = [NSMutableArray arrayWithArray:_items];
        [array removeObject:cellGhost_.text];
        _items = array;
        [self.tableView deleteRowsAtIndexPaths:@[cellChostIndexPath_] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (NSString*)linkedFieldText {
    if (_linkedTextField) {
        return _linkedTextField.text;
    } else {
        return _linkedLabel.text;
    }
}

- (void)setLinkedFieldText:(NSString*)text {
    if (_linkedTextField) {
        _linkedTextField.text = text;
    } else {
        _linkedLabel.text = text;
    }
}

- (UIFont*)linkedFieldFont {
    if (_linkedTextField) {
        return _linkedTextField.font;
    } else {
        return _linkedLabel.font;
    }
}

- (UIColor*)linkedFieldTextColor {
    if (_linkedTextField) {
        return _linkedTextField.textColor;
    } else {
        return _linkedLabel.textColor;
    }
}

- (CGRect)linkedFieldFrame {
    if (_linkedTextField) {
        return _linkedTextField.frame;
    } else {
        return _linkedLabel.frame;
    }
}

- (CGFloat)cellHeight {
    if (_linkedTextField) {
        return _linkedTextField.frame.size.height * 1.5; /// set cell height here  claus!
    } else {
        return _linkedLabel.frame.size.height * 1.5;
    }
}

- (void)dealloc {
    [_linkedTextField removeTarget:self action:@selector(textFieldValueChanged) forControlEvents:UIControlEventEditingChanged];
}

@end
