//
//  TabBar.m
//  TabBar
//
//  Created by Developer on 2/27/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "TabBar.h"

@implementation TabBar

@synthesize delegate;


#define LEFT_LIMIT 98.5  
#define RIGHT_LIMIT 220.5
#define MIDDLE_LIMIT 160.0

bool move;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //days
        days=[[NSArray alloc] initWithObjects:@"Fri",@"Sat",@"Sun",@"Mon",@"Tu",@"Wed",@"Thu",@"Fri",@"Sat",@"Sun",@"Mon",@"Tu",@"Wed", nil];
       
        //background bar
        UIImageView *bar=[[UIImageView alloc] initWithFrame: CGRectMake(0, 0, 320, 43)];
        bar.image=[UIImage imageNamed:@"camera_button_bg.png"];
        [self addSubview:bar];
       
        //slider track
        UIImageView *sliderBar=[[UIImageView alloc] initWithFrame:CGRectMake(68,5,183,31)];
        sliderBar.image=[UIImage imageNamed:@"slider_track.png"];
        [self addSubview:sliderBar];
     
        //sliderScroll
        sliderScroll=[self generateSliderScroll];
        [self addSubview: sliderScroll];
     
        //sliderButton
        sliderButton=[UIButton buttonWithType:UIButtonTypeCustom];
        sliderButton.frame=CGRectMake(130,-1, 61, 43);
        UIImageView *backgroundImage=[[UIImageView alloc] initWithFrame:CGRectMake(0, 6, 61, 31)];
        backgroundImage.image=[UIImage imageNamed:@"slider_button.png"];
        [sliderButton addSubview:backgroundImage];
        [sliderButton setTitleColor: [UIColor blackColor] forState:UIControlStateNormal];
        sliderButton.titleLabel.font=[UIFont boldSystemFontOfSize:15.0f];
        [self addSubview:sliderButton];
      
        //leftArrow
        leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
        leftButton.frame=CGRectMake(17, 11.5f, 44, 43);
         UIImageView *bgArrowLeft=[[UIImageView alloc] initWithFrame:CGRectMake(13, 0, 11, 16)];
         bgArrowLeft.image=[UIImage imageNamed:@"arrow_left.png"];
        [leftButton addSubview:bgArrowLeft];
        [leftButton addTarget:self action:@selector(shiftLeft:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:leftButton];
    
        //rightArrow  
        rightButton=[UIButton buttonWithType:UIButtonTypeCustom];
        rightButton.frame=CGRectMake(268, 11.5f, 44, 43);
        UIImageView *bgArrowRight=[[UIImageView alloc] initWithFrame:CGRectMake(13, 0, 11, 16)];
        bgArrowRight.image=[UIImage imageNamed:@"arrow_right.png"];
        [rightButton addSubview:bgArrowRight];
        [rightButton addTarget:self action:@selector(shiftRight:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:rightButton];
    
        //dragGestureRecognizer
        // we add a pang gesture recognizer, the only view that will respond to this gesture recognizer will be the sliderButton
        UIPanGestureRecognizer *panRecognizer=[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handleDrag:)];
        panRecognizer.delegate=self;
        [panRecognizer setMinimumNumberOfTouches:1];
        [panRecognizer setMaximumNumberOfTouches:1];
        [self addGestureRecognizer:panRecognizer];

    }
    return self;
}

//returns our slider scroll containing the days of the week
-(UIScrollView*) generateSliderScroll 
{
    UIScrollView *scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(68, 5, 183, 31)];
    scrollView.contentSize=CGSizeMake(13*61, 31); //content size is different from the frame size (what is actually displayed)
    scrollView.pagingEnabled=YES;
    scrollView.scrollEnabled=NO;
    scrollView.delegate=self; // we will handle the scrolling events
    for (int i=0;i<13;i++)
    {
        UIButton *button=[self createButton:[days objectAtIndex:i] withX:i*61 withY:0];  // for each day of the week we create a different button
        [scrollView addSubview:button];
    }
    return scrollView;
}

//gets called everytime a "day" button is pressed
-(void)changeDay:(id) sender
{
    UIButton *pressed=(UIButton *) sender; // we get the sender
    CGPoint center=[self.superview convertPoint:pressed.center fromView:sliderScroll];   // get the center of the pressed button in parent view's coordinates
    if (center.x==LEFT_LIMIT) {  //presed previous day
        [self animate:CGPointMake(LEFT_LIMIT, sliderButton.center.y) withTitle:[days objectAtIndex:--index] withSpeed:0.3];  // we animate the sliderButton to the left
        [self performSelector:@selector(delayedScrollingLeft) withObject:nil afterDelay:0.3]; // we call scroll the sliderScroll to the left by calling delayedScrollingLeft with 0.3 delay
    }
    if (center.x==RIGHT_LIMIT) { //pressed next day
        [self animate:CGPointMake(RIGHT_LIMIT, sliderButton.center.y) withTitle:[days objectAtIndex:++index] withSpeed:0.3];  // we animate the sliderButton to the right
        [self performSelector:@selector(delayedScrollingRight) withObject:nil afterDelay:0.3]; // we call scroll the sliderScroll to the right by calling delayedScrollingRight with 0.3 delay
    }
}

//if the scrollSlider finished scrolling
-(void) scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    rightButton.enabled=YES; //we enable the arrows again (as they were disabled while the scrollSlider was scrolling)
    leftButton.enabled=YES;
    if (scrollView.contentOffset.x==10*61) { // if we reached the right end of the scrolling content we set the content offset to 3*61 without animation (circular trick)
        move=NO;
        [scrollView setContentOffset:CGPointMake(3*61,scrollView.contentOffset.y) animated:NO];
        [self performSelector:@selector(changeSlideValue) withObject:nil afterDelay:0.1];
        index=4;
    }
    if (scrollView.contentOffset.x==0){// if we reached the left end of the scrolling content we set the content offset to 7*61 without animation (circular trick)
        move=NO;
        [scrollView setContentOffset:CGPointMake(7*61,scrollView.contentOffset.y) animated:NO];
        index=8;
        [self performSelector:@selector(changeSlideValue) withObject:nil afterDelay:0.1];
    }
}

// we create a button for each day of the week: we are passing the button title, and the frame origin as parameters
-(UIButton *)createButton:(NSString*) title withX:(CGFloat)x withY:(CGFloat)y
{
    UIButton* button=[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(x, y, 61, 31);
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:0.6f green:0.6f blue:0.6f alpha:1.0f] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(changeDay:) forControlEvents:UIControlEventTouchUpInside]; // changeDay will be called everytime the button is pressed
    button.backgroundColor = [UIColor clearColor];
    button.titleLabel.font=[UIFont boldSystemFontOfSize:15.0f];
    return button;
}

//left arrow is pressed

-(void)shiftLeft:(id) sender
{
    leftButton.enabled=NO;  // we disable the arrow so it won't get pressed while the slider scrolls 
    [self animate:CGPointMake(LEFT_LIMIT, sliderButton.center.y) withTitle:[days objectAtIndex:--index] withSpeed:0.3]; 
    [self performSelector:@selector(delayedScrollingLeft) withObject:nil afterDelay:0.3];
}

//right arrow is pressed
-(void)shiftRight:(id)sender
{
    rightButton.enabled=NO; // we disable the arrow so it won't get pressed while the slider scrolls
    [self animate:CGPointMake(RIGHT_LIMIT, sliderButton.center.y) withTitle:[days objectAtIndex:++index]withSpeed:0.3];
    [self performSelector:@selector(delayedScrollingRight) withObject:nil afterDelay:0.3];
}

// only the sliderButton should respond to the gesture recognizer
-(BOOL)gestureRecognizer:(UIGestureRecognizer*) gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (touch.view == sliderButton)
        return YES;
    return NO;
}

//handling the drags
-(void) handleDrag:(UIPanGestureRecognizer*)panGestureRecognizer
{
    
    if (panGestureRecognizer.state==UIGestureRecognizerStateBegan)
    {
        
    }
    if (panGestureRecognizer.state==UIGestureRecognizerStateChanged) // this is called everytime the touches are moving
    {
        CGPoint touchPoint=[panGestureRecognizer locationOfTouch:0  inView:self];
        if (CGRectContainsPoint(sliderButton.frame, touchPoint))  // if the touch point is in the sliderButton's frame
        {
            if (touchPoint.x > LEFT_LIMIT && touchPoint.x< RIGHT_LIMIT)  // we check if we are in our slidertrack's limits
            {
                CGPoint nextPoint=CGPointMake(touchPoint.x, sliderButton.center.y);
                sliderButton.center=nextPoint;
            }
            if (touchPoint.x >= RIGHT_LIMIT) // if we passed the right limit while touching, the sliderButton will be on the right limit of the track 
                sliderButton.center=CGPointMake(RIGHT_LIMIT,sliderButton.center.y);
            if (touchPoint.x <=LEFT_LIMIT) // same as the other, only this time the left limit
                sliderButton.center=CGPointMake(LEFT_LIMIT,sliderButton.center.y);
        }
            
    }
    if(panGestureRecognizer.state==UIGestureRecognizerStateEnded)  // touches finished
    {

        if (CGRectContainsPoint(sliderButton.frame, CGPointMake(LEFT_LIMIT, sliderButton.center.y))) { // if we over the left_limit, we slide it to the left
            [self animate:CGPointMake(LEFT_LIMIT, sliderButton.center.y) withTitle:[days objectAtIndex:--index] withSpeed:0.15]; 
            [self performSelector:@selector(delayedScrollingLeft) withObject:nil afterDelay:0.15];
        }
        if (CGRectContainsPoint(sliderButton.frame, CGPointMake(RIGHT_LIMIT, sliderButton.center.y))) { // slide it to the right
            [self animate:CGPointMake(RIGHT_LIMIT, sliderButton.center.y) withTitle:[days objectAtIndex:++index]withSpeed:0.15];
            [self performSelector:@selector(delayedScrollingRight) withObject:nil afterDelay:0.15];

        }
        if (CGRectContainsPoint(sliderButton.frame, CGPointMake(MIDDLE_LIMIT, sliderButton.center.y))) //slide it in the middle
            [self animate:CGPointMake(MIDDLE_LIMIT, sliderButton.center.y) withTitle:[days objectAtIndex:index]withSpeed:0.3];

    }
}

//scroll the slider to the left
-(void) delayedScrollingLeft 
{
    offset=sliderScroll.contentOffset.x;//initial offset
    centerOfSlider=sliderButton.center.x;
    [sliderScroll setContentOffset:CGPointMake(offset-61, sliderScroll.contentOffset.y) animated:YES];
    [delegate dayChanged:-1]; //notify the delegate
}

//scroll the slider to the right
-(void) delayedScrollingRight 
{
    offset=sliderScroll.contentOffset.x; //initial offset
    centerOfSlider=sliderButton.center.x;
    [sliderScroll setContentOffset:CGPointMake(offset+61, sliderScroll.contentOffset.y) animated:YES];
    [delegate dayChanged:1]; //notify the delegate
}

//animate to a given destination, with a title and a given speed
-(void) animate: (CGPoint) destination withTitle:(NSString*) title withSpeed:(CGFloat) speed
{
    [sliderButton setTitle:title forState:UIControlStateNormal];
    [sliderButton setTitle:title forState:UIControlStateHighlighted];
    [UIView beginAnimations:@"Transit" context:NULL];
    [UIView setAnimationDuration:speed];
     sliderButton.center=destination;
    [UIView commitAnimations];
    
}

//setting the current day
//comment
-(void) setDay:(NSInteger)day
{
    index=day+1;
    move=NO;
    [sliderScroll setContentOffset:CGPointMake((index-1)*61, sliderScroll.contentOffset.y) animated:NO];
    [self performSelector:@selector(changeSlideValue) withObject:nil afterDelay:0.1];
    [sliderButton setTitle:[days objectAtIndex:index] forState:UIControlStateNormal];
    [sliderButton setTitle:[days objectAtIndex:index] forState:UIControlStateHighlighted];

}

//the slider button whill move at the same time with the slider
-(void) scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (move==YES) // it should only move when it performs an animated scrolling   
        sliderButton.center=CGPointMake(centerOfSlider+offset-scrollView.contentOffset.x, sliderButton.center.y);
}

-(void) changeSlideValue
{
    move=YES;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

@end
