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

#import "RootViewController.h"
#import "TabBar.h"
#import "Course.h"
#import "CourseDetailsViewController.h"
#import "Cell.h"



@implementation RootViewController

bool slide; // we will use this boolean value to check if we have only the following courses section, or both of them


- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    //setting the date
    date=[NSDate date];   //current date
    formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    int dayOfWeek = [[[NSCalendar currentCalendar] components:NSWeekdayCalendarUnit fromDate:date] weekday];    // number of day in week (Sun=1, Sat=7)
  
    //add the bottom tabBar
    TabBar *tab=[[TabBar alloc] initWithFrame:CGRectMake(0, 374, 320, 43)];
    [tab setDay:dayOfWeek];  // setting the slider according to the current date
    tab.delegate=self;     //the delaget of the tabbar is rootViewController, everyday the slider moves, dayChanged is called
    [self.view addSubview:tab];
    
    //setting the "repository"
    
    previousCourses=[[NSArray alloc] initWithObjects:[[Course alloc] initWithFields:@"LCE7312" withTitle:@"English for special puposes C1.2" withTeacher:@"Romenski Aleksandr" withHour:@"08:00 - 10:00"] , [[Course alloc] initWithFields:@"LCI6112" withTitle:@"Italian A1" withTeacher:@"Reno Vittoriano" withHour:@"10:15 - 11:45"], nil];
    nextCourses=[[NSArray alloc] initWithObjects:[[Course alloc] initWithFields:@"STP6002" withTitle:@"Social policy" withTeacher:@"Kikas Margo" withHour:@"12:00 - 14:00"] , [[Course alloc] initWithFields:@"STL7015" withTitle:@"Legal Basis of Child Protection" withTeacher:@"Kuslap Karin" withHour:@"15:30 - 17:00"], nil];
   
    //previousLabel
    UILabel *previousLabel=[[UILabel alloc] initWithFrame:CGRectMake(70,3,100,15)];
    previousLabel.backgroundColor=[UIColor clearColor];
    previousLabel.text=@"Previous";
    previousLabel.font=[UIFont boldSystemFontOfSize:14];
    previousLabel.textColor=[UIColor colorWithRed:(82/255.0) green:(82/255.0) blue:(82/255.0) alpha:1.0];
    
    //sliderButton
    sliderButton=[UIButton buttonWithType:UIButtonTypeCustom];
    sliderButton.frame=CGRectMake(62, 0, 195, 23);
    [sliderButton setBackgroundImage:[UIImage imageNamed:@"tab.png"] forState:UIControlStateNormal]; 
    [sliderButton setBackgroundImage:[UIImage imageNamed:@"tab.png"] forState:UIControlStateHighlighted]; 
    [sliderButton addTarget:self action:@selector(slide:) forControlEvents:UIControlEventTouchUpInside];
    [sliderButton addSubview:previousLabel];
    
    // tableView
    coursesTable=[[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 417) style:UITableViewStylePlain];
    coursesTable.autoresizingMask=UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleHeight;
    coursesTable.delegate=self;   //the rootViewController will handle all the tableview's "events"
    coursesTable.dataSource=self;  // the rootViewController will provide the data source of the tableview
    coursesTable.separatorStyle=UITableViewCellSeparatorStyleNone;
    coursesTable.backgroundColor=[UIColor colorWithRed:(232/255.0) green:(232/255.0) blue:(232/255.0) alpha:1.0];
   
    slide=NO; //initially the slider is off
   
    [self.view setBackgroundColor:[UIColor colorWithRed:(232/255.0) green:(232/255.0) blue:(232/255.0) alpha:1.0]];
    [self.view addSubview:coursesTable];
    [self.view addSubview:sliderButton];
    
    [coursesTable reloadData];


}

// this returns the number of sections according to the value of "slide"

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
    if (slide==YES) return 2;
    return 1;
}

//number of rows in section
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    if (slide==NO)   // if only the following courses are displayed
        return [nextCourses count];
    else {
        if (section==0)  //if we are in the previous section
            return [previousCourses count];
        return [nextCourses count];   // following section
    }
}

//provides a cell for a given indexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *prevIdentifier=@"Prev";
    static NSString *nextIdentifier=@"Next";
    Cell *cell; //the cell that will be returned
    Course *course; //current course that will be displayed
    CGRect frame=CGRectMake(3, 8, 314, 84);  //frame of the cell
    NSString *imageName=@"list_item_active.png";  // we assume that the cell is going to be in the next courses section
    
    if (slide==YES) {  // if both of the sections are displayed
        if (indexPath.section==0)  // previous section
        {
            cell=[tableView dequeueReusableCellWithIdentifier:prevIdentifier];  //we try to find a cell that is offscreen and reuse it
            if (cell==nil) // if we cannot find a reusable cell
                cell=[[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:prevIdentifier];  
            cell.contentView.backgroundColor=[UIColor colorWithRed:(139/255.0) green:(139/255.0) blue:(139/255.0) alpha:1.0];  //background color of the cell
            course=[previousCourses objectAtIndex:indexPath.row];  // current course that will be displayed
            imageName=@"list_item_next.png";  // background image for previous course
    

        }
        else   // next section
        {
            cell=[tableView dequeueReusableCellWithIdentifier:nextIdentifier];  //reusable cell
            if (cell==nil)
                    cell=[[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nextIdentifier];
            course=[nextCourses objectAtIndex:indexPath.row]; // current course that will be displayed
        }

    }
    else {  // only the next section is displayed
            cell=[tableView dequeueReusableCellWithIdentifier:nextIdentifier]; //reusable cell
            if (cell==nil)
                cell=[[Cell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nextIdentifier];
            course=[nextCourses objectAtIndex:indexPath.row];
    }
    
    [cell setFields:frame withImage:imageName withId:course.idCourse withTitle:course.title withTeacher:course.teacher withHours:course.hour];  //set cell's properties
    return cell;
}

//height for a row
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

// create an "empty" header in order to have an appropriate space between sections
-(UIView*) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
    return headerView;
}


//height for a header
-(CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section 
{
    if(slide==YES)  //both sections displayed
    {
        if (section==1)  //header only for next section
            return 40;
        return 0;
    }
    return 40; //next section only

}


//when sliderButton is pressed
-(void) slide:(id) sender
{
    if (slide==YES) //if both of the sections are displayed, animate the previous section offscreen
        [coursesTable setContentOffset:CGPointMake(0, [previousCourses count]*100) animated:YES]; 
    else {  //if only the next section is displayed
        slide=YES; //change value of slide
        CGPoint offset=coursesTable.contentOffset;  //get the current offset
        [coursesTable reloadData]; // reload data but keep the previous section offscreen
        coursesTable.contentOffset=CGPointMake(offset.x, offset.y+[previousCourses count]*100);  //keep previous section offscreen while reloading data
        [coursesTable setContentOffset:offset animated:YES]; //slide previous courses onscreen after reloading data
        
    }

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

// cell selection handling
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row=indexPath.row; //current row
    int section=indexPath.section; //current section
    Course *course=[nextCourses objectAtIndex:row]; //current course
    CourseDetailsViewController *detailViewController=[[CourseDetailsViewController alloc] init ]; //create course detail view controller
    if (section==0 && slide==YES) //if a previoius cell has been selected
            course=[previousCourses objectAtIndex:row];
    detailViewController.courseId=course.idCourse;   //set detailView controller properties 
    detailViewController.courseTitle=course.title;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:nil action:nil]; //navigation back button
    [self.navigationController pushViewController:detailViewController animated:YES];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation ==UIInterfaceOrientationPortrait);
}

//every time the table view is scrolling

-(void) scrollViewDidScroll:(UIScrollView *)scrollView {
   if (slide==YES) //if both sections are displayed
      sliderButton.center=CGPointMake(sliderButton.center.x,[previousCourses count]*100-coursesTable.contentOffset.y+11.5); //slide the sliderButton at the same time with the table view
}

//after the scroll view ended scrolling (scrolling is different from dragging !)

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    if (sliderButton.center.y==11.5)  // if we can delete the previous section : that means the slider Button is in the initial position 
    {
        slide=NO; // the slide value must be changed
        [coursesTable beginUpdates];
        [coursesTable deleteSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation: UITableViewRowAnimationTop];  //delete the previous section
        [coursesTable endUpdates];
    }

}

// tab bar custom control calls this method everytime the day has been changed
-(void) dayChanged:(NSInteger)day  
{
    NSDateComponents *dayComponent = [[NSDateComponents alloc] init]; //create a date component
    dayComponent.day = day; // set the day: -1 if we need the previous day, 1 if we need the following day
    date = [[NSCalendar currentCalendar] dateByAddingComponents:dayComponent toDate:date options:0]; //modify the day
    NSLog([formatter stringFromDate:date]);
        
}

@end
