//
//  CustomSegmentControl.m
//  DrivoMeter
//
//  Created by Triin Uudam on 4/8/12.
//  Copyright (c) 2012 Mobi Solutions OÜ. All rights reserved.
//

#import "CustomSegmentControl.h"

@implementation CustomSegmentedControl


-(id)initWithItems:(NSArray *)items offColor:(UIColor*)offcolor onColor:(UIColor*)oncolor {
  if (self = [super initWithItems:items]) {
    // Initialization code
    offColor = offcolor;
    onColor = oncolor;
    hasSetSelectedIndexOnce = YES;
    [self setInitialMode];
    [self setSelectedSegmentIndex:0];  // default to first button, or the coloring gets all whacked out :(
  }
  return self;
}

-(void)setInitialMode
{
  // set essential properties
  [self setBackgroundColor:[UIColor clearColor]];
  [self setSegmentedControlStyle:UISegmentedControlStyleBar];
  
  // loop through children and set initial tint
  for( int i = 0; i < [self.subviews count]; i++ )
  {
    [[self.subviews objectAtIndex:i] setTintColor:nil];
    [[self.subviews objectAtIndex:i] setTintColor:offColor];
  }
  [[self.subviews objectAtIndex:0] setTintColor:onColor];
  // listen for updates
  [self addTarget:self action:@selector(setToggleHiliteColors) forControlEvents:UIControlEventValueChanged];
}

-(void)setToggleHiliteColors
{
  // get current toggle nav index
  int index = self.selectedSegmentIndex;
  int numSegments = [self.subviews count];
  
  for( int i = 0; i < numSegments; i++ )
  {
    // reset color
    [[self.subviews objectAtIndex:i] setTintColor:nil];
    [[self.subviews objectAtIndex:i] setTintColor:offColor];
  }
  
  if( hasSetSelectedIndexOnce )
  {
    // this is super weird - the subviews array is backwards... so deal with it like that
    [[self.subviews objectAtIndex: numSegments - 1 - index] setTintColor:onColor];
  }
  else
  {
    // ...but the very first time, they're the expected order :-/
    [[self.subviews objectAtIndex: index] setTintColor:onColor];
    hasSetSelectedIndexOnce = YES;
  }
  
}

- (void)updateSegments {
  [self setToggleHiliteColors];
}

@end 
