//
//  MedicalPackageTVController.m
//  as350b3e
//
//  Created by Vadim Dagman on 4/3/14.
//
//

#import "MedicalPackageTVController.h"
#import "MedicalPackage.h"
#import "MedicalItemCell.h"

#define NSLog(...)

@interface MedicalPackageTVController () {
    CGFloat rowHeight_;
}

@end

@implementation MedicalPackageTVController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    UITableViewCell* cell = [self.tableView dequeueReusableCellWithIdentifier:@"medicalItemCell"];
    rowHeight_ = cell.frame.size.height;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)setPackage:(MedicalPackage *)package {
    _package = package;
    [self.tableView reloadData];
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    NSInteger count = _package.items.count * _package.selected;
    return count;
}

- (void)viewDidLayoutSubviews {
    self.tableView.frame = self.tableView.superview.bounds;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MedicalItemCell *cell = (MedicalItemCell*)[tableView dequeueReusableCellWithIdentifier:@"medicalItemCell" forIndexPath:indexPath];

    // Configure the cell...
    cell.delegate = self;
    cell.item = _package.items[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    CGRect frame = cell.frame;
    frame.size.width = _tableView.frame.size.width;
    cell.frame = frame;
    return cell;
}

- (CGFloat)tableHeightForMedicalPackage:(MedicalPackage *)package {
    return package.items.count * rowHeight_ * package.selected;
}

#pragma mark- MedicalItemCellProtocol

- (void)cellDeleted:(UITableViewCell *)cell {
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    [_package deleteItem:((MedicalItemCell*)cell).item];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    
    [_delegate sizeChanged];
}

@end
