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

#import "MedicalListTVController.h"
#import "MedicalPackageCell.h"
#import "CommonDefs.h"
#import "EquipmentPackages.h"


@interface MedicalListTVController () {
    MedicalPackageCell* sampleCell_;
    __weak IBOutlet UIView *headerView_;
    __weak IBOutlet UIView *footerView_;
    __weak IBOutlet UILabel *totalWeightLabel_;
    __weak IBOutlet UILabel *totalArmLabel_;
    __weak IBOutlet UILabel *totalMomentLabel_;
    __weak IBOutlet UILabel *totalArmLatLabel_;
    __weak IBOutlet UILabel *totalMomentLatLabel_;
    __weak IBOutlet UIButton *createNewPackageButton_;
}

@end

@implementation MedicalListTVController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    sampleCell_ = [self.tableView dequeueReusableCellWithIdentifier:@"medicalPackageCell"];
    sampleCell_.parentController = self;
    
    [self observeKeyboard];
    createNewPackageButton_.layer.cornerRadius = 7;
    createNewPackageButton_.layer.borderWidth = 1;
    createNewPackageButton_.layer.borderColor = [UIColor whiteColor].CGColor;
}

- (void)didMoveToParentViewController:(UIViewController *)parent {
    [self.parentViewController.view addSubview:headerView_];
    [self.view.superview addSubview:footerView_];
    
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    CGRect frame = headerView_.frame;
    frame.size.width = self.view.frame.size.width;
    frame.origin.y = 20; //Leave room for status bar
    headerView_.frame = frame;
    
    
    frame = footerView_.frame;
    frame.origin.y = self.view.superview.frame.size.height - footerView_.frame.size.height;
    frame.size.width = self.view.frame.size.width;
    footerView_.frame = frame;
    
    frame = self.view.superview.bounds;
    
    frame.origin.y = headerView_.frame.size.height;
    frame.size.height = frame.size.height - headerView_.frame.size.height - footerView_.frame.size.height;
    self.view.frame = frame;
//    NSLog(@"Table view height: %f", self.view.frame.size.height);
    
}

- (void)setEquipmentPackages:(EquipmentPackages *)equipmentPackages {
    _equipmentPackages = equipmentPackages;
    [self addObservers];
    [self.tableView reloadData];
    
    totalWeightLabel_.text = _equipmentPackages.totalWeightString;
    totalArmLabel_.text = _equipmentPackages.totalArmString;
    totalArmLatLabel_.text = _equipmentPackages.totalArmLatString;
    totalMomentLabel_.text = _equipmentPackages.totalMomentString;
    totalMomentLatLabel_.text = _equipmentPackages.totalMomentLatString;
}

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

- (BOOL)shouldAutorotate {
    return YES;
}

//- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
//    [self.tableView reloadData];
//}
//
- (void)dealloc {
    [self removeObservers];
}

- (void)addObservers {
    [_equipmentPackages addObserver:self forKeyPath:@"totalWeight" options:NSKeyValueObservingOptionNew context:nil];
    [_equipmentPackages addObserver:self forKeyPath:@"totalMoment" options:NSKeyValueObservingOptionNew context:nil];
    [_equipmentPackages addObserver:self forKeyPath:@"totalMomentLat" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)removeObservers {
    [_equipmentPackages removeObserver:self forKeyPath:@"totalWeight"];
    [_equipmentPackages removeObserver:self forKeyPath:@"totalMoment"];
    [_equipmentPackages removeObserver:self forKeyPath:@"totalMomentLat"];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    totalWeightLabel_.text = _equipmentPackages.totalWeightString;
    totalArmLabel_.text = _equipmentPackages.totalArmString;
    totalArmLatLabel_.text = _equipmentPackages.totalArmLatString;
    totalMomentLabel_.text = _equipmentPackages.totalMomentString;
    totalMomentLatLabel_.text = _equipmentPackages.totalMomentLatString;
}

#pragma mark- Service Methods

- (void)observeKeyboard {
    [[NSNotificationCenter defaultCenter] addObserverForName:TEXT_FIELD_WILL_BEGIN_EDITING object:nil queue:nil usingBlock:^(NSNotification *note) {
        UITextField* textField = note.object;
        __block id keyboardNotification = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardWillShowNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
            [[NSNotificationCenter defaultCenter] removeObserver:keyboardNotification];
            
            NSDictionary* keyboardInfo = [note userInfo];
            CGSize kbSize = [[keyboardInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
            
            CGPoint origin = textField.frame.origin;
            origin = [self.view convertPoint:origin fromView:textField.superview];
            origin.y += textField.frame.size.height; // This is no longer an origin, but a bottom point of the textfield in the coordinate space of this view
            
            // If active text field is hidden by keyboard, scroll it so it's visible
            CGRect aRect = self.view.frame;
            CGPoint contentOffset = self.tableView.contentOffset;
            origin.y -= contentOffset.y; // Converted point is calculated form the content start of the table/scroll view, not from the visible frame
            CGFloat keyBoardHeight = kbSize.height > kbSize.width ? kbSize.width : kbSize.height; // For landscape the dimensions may be swapped
            aRect.size.height -= keyBoardHeight - footerView_.frame.size.height;
            CGFloat offsetToKeyboard = origin.y - aRect.size.height;
            if (offsetToKeyboard > 0) {
                contentOffset.y += offsetToKeyboard + 20; // with little margin
                [self.tableView setContentOffset:contentOffset animated:YES];
            }
            
            __block id keyboardHideNotification = [[NSNotificationCenter defaultCenter] addObserverForName:UIKeyboardDidHideNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
                [[NSNotificationCenter defaultCenter] removeObserver:keyboardHideNotification];
                
                if (self.tableView.contentOffset.y != 0 && self.tableView.contentSize.height - self.tableView.contentOffset.y < self.tableView.frame.size.height) {
                    CGPoint contentOffset;
                    contentOffset.y = self.tableView.contentSize.height - self.tableView.frame.size.height;
                    [self.tableView setContentOffset:contentOffset animated:YES];
                }
            }];
            
        }];
    }];
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return _equipmentPackages.packages.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Configure the cell...
    MedicalPackageCell *cell = (MedicalPackageCell*)[tableView dequeueReusableCellWithIdentifier:@"medicalPackageCell" forIndexPath:indexPath];
    MedicalPackageCell* medicalPackageCell = (MedicalPackageCell*)cell;
    medicalPackageCell.parentController = self;
    medicalPackageCell.package = _equipmentPackages.packages[indexPath.row];
    medicalPackageCell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = [sampleCell_ cellHeightForPackage:_equipmentPackages.packages[indexPath.row]];
    //NSLog(@"heightForRowAtIndexPath: Height for cell:%@ %f", indexPath, height);
    return height;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
   
    MedicalPackageCell* medicalPackageCell = (MedicalPackageCell*)cell;
    if (indexPath.row%2) {
        medicalPackageCell.contentView.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1];
    } else {
        medicalPackageCell.contentView.backgroundColor = [UIColor blackColor];
    }
    
   // NSLog(@"willDisplayCell: Height for cell:%@ %f", indexPath, cell.frame.size.height);
}
- (void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    MedicalPackageCell* medicalPackageCell = (MedicalPackageCell*)cell;
    medicalPackageCell.package = nil;
}

- (IBAction)closeAction:(id)sender {
    [self.parentViewController dismissViewControllerAnimated:YES completion:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"EquipmentControllerDismissed" object:nil];
}

- (IBAction)createNewPackageAction:(id)sender {
    [_equipmentPackages createNewPackage];
    
    NSIndexPath* indexPath = [NSIndexPath indexPathForRow:_equipmentPackages.packages.count-1 inSection:0];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationBottom];
    [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    [self updateVisibleCells];
}

- (void)updateVisibleCells {
    NSArray* visibleCells = [self.tableView visibleCells];
    for (UITableViewCell* cell in visibleCells) {
        NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
        if (indexPath.row%2) {
            cell.contentView.backgroundColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1];
        } else {
            cell.contentView.backgroundColor = [UIColor blackColor];
        }
    }
}


#pragma mark- MedicalPackageCellProtocol

- (void)cellSizeChanged:(UITableViewCell *)cell {
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)cellDeleted:(UITableViewCell *)cell {
    NSIndexPath* indexPath = [self.tableView indexPathForCell:cell];
    [_equipmentPackages deletePackage:((MedicalPackageCell*)cell).package];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    [self updateVisibleCells];
}

@end
