//
//  VDLabelWithDropDown.m
//  EC145
//
//
//  Created by Claus Richter on 4/21/14.
//  Copyright (c) 2014 Claus Richter. All rights reserved.
//

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

@implementation VDLabelWithDropDown {
    UIPopoverController* popover_;
    VDTableViewForPopover* tableViewForPopover_;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = self.bounds;
        [self addSubview:button];
        self.userInteractionEnabled = YES;
        [button addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchUpInside];
        self.text = @"";
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIButton* button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = self.bounds;
        [self addSubview:button];
        [button addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventTouchDragInside];
        self.text = @"";
    }
    return self;
}

- (void)showPopover {
    
    NSLog(@"showPopover");
    
    
    if (!_items.count) return;
    
    if (!popover_) {
        tableViewForPopover_ = [[VDTableViewForPopover alloc] init];
        tableViewForPopover_.linkedLabel = self;
        tableViewForPopover_.fixedTable = YES;
        tableViewForPopover_.items = self.items; // Make it reload th eitems and clear past selection
        popover_ = [[UIPopoverController alloc] initWithContentViewController:tableViewForPopover_];
        popover_.delegate = self;
    }
    tableViewForPopover_ = (VDTableViewForPopover*)popover_.contentViewController;
    tableViewForPopover_.items = self.items; // Make it reload th eitems and clear past selection
    CGFloat height = MAX(60,tableViewForPopover_.height);
    popover_.popoverContentSize = CGSizeMake(self.frame.size.width + 40, height);
    [popover_ presentPopoverFromRect:self.frame inView:self.superview permittedArrowDirections:UIPopoverArrowDirectionLeft|UIPopoverArrowDirectionRight animated:YES];
}

- (void)dismissPopover {
    [popover_ dismissPopoverAnimated:YES];
    if (_dropDownDelegate) {
        [_dropDownDelegate dropDownSelectionChanged:self];
    }
}


- (void)buttonClicked {
    [self showPopover];
}

@end
