//
//  OdometerPickerView.m
//  DrivoMeter
//
//  Created by Triin Uudam on 3/18/12.
//  Copyright (c) 2012 Mobi Solutions OÜ. All rights reserved.
//

#import "OdometerPickerView.h"
#import "Constants.h"

@interface OdometerPickerView (Private)
- (NSString *)newValueForPicker;
@end
@implementation OdometerPickerView

@synthesize picker = picker_;
@synthesize delegate = delegate_;
@synthesize parentView = parentView_;



- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
  return 8;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
  return 10;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
  
  NSString *title = [NSString stringWithFormat:@"%d",row];
  
  return title;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component {
  int sectionWidth = 30;
  
  return sectionWidth;
}

- (void)showPickerOnView:(UIView *)view {
  [self setParentView:view];
  [self setFrame:CGRectMake(view.frame.origin.x,
                                   view.frame.origin.y + view.frame.size.height,
                                   self.frame.size.width,
                                   self.frame.size.height)];
  [UIView commitAnimations];
  [view addSubview:self];
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.3];
  [view bringSubviewToFront:self];
  [self setFrame:CGRectMake(view.frame.origin.x,
                                   view.frame.size.height - self.frame.size.height,
                                   self.frame.size.width,
                                   self.frame.size.height)];
  MSLog(@"pickerview frame %@", NSStringFromCGRect(picker_.frame));
  [UIView commitAnimations];
}

- (void)hidePickerFromView:(UIView *)view {
  [UIView beginAnimations:nil context:nil];
  [UIView setAnimationDuration:0.3];
  [self setFrame:CGRectMake(view.frame.origin.x,
                                   view.frame.origin.y + view.frame.size.height,
                                   self.frame.size.width,
                                   self.frame.size.height)];
  [UIView commitAnimations];
  [self removeFromSuperview];
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
  NSString *newValue = [self newValueForPicker];
  [self.delegate updateOdometerValue:newValue];
}

- (NSString *)newValueForPicker {
  NSMutableString *result = [[NSMutableString alloc] init];
  for (int i = 0; i < [picker_ numberOfComponents]; i++) {
    int value = [picker_ selectedRowInComponent:i];
    MSLog(@"value %d", value);
    [result appendString:[NSString stringWithFormat:@"%d", value]];
  }
  return [NSString stringWithString:result];
}

- (IBAction)doneButtonPressed:(id)sender {
  [self hidePickerFromView:parentView_];
}
@end
