//
//  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


-(id)initWithRoomNumber:(NSString*) roomNo 
{
    self=[super init];
    if (self)
    {
        room=roomNo;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    //setting the date and dateLabel
    date=[NSDate date];   //current date
    formatter=[[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd.MM.yyyy"];
    dateLabel= [[UILabel alloc] initWithFrame:CGRectMake(116, 35, 100, 15)];
    dateLabel.text=[formatter stringFromDate:date];
    dateLabel.textColor=[UIColor colorWithRed:(120/255.0) green:(120/255.0) blue:(120/255.0) alpha:1.0];
    dateLabel.backgroundColor=[UIColor colorWithRed:(232/255.0) green:(232/255.0) blue:(232/255.0) alpha:1.0];
    dateLabel.font=[UIFont boldSystemFontOfSize:18];
    
    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, 44)];
    [tab setDay:dayOfWeek];  // setting the slider according to the current date
    tab.delegate=self;     //the delegate of the tabbar is rootViewController, everyday the slider moves, dayChanged is called

    //setting the "repository"
    parser=[[XMLParser alloc] init];
   
    //previousLabel
    UILabel *previousLabel=[[UILabel alloc] initWithFrame:CGRectMake(20,3,152,15)];
    previousLabel.backgroundColor=[UIColor clearColor];
    previousLabel.text=@"Previous lectures";
    previousLabel.font=[UIFont boldSystemFontOfSize:14];
    previousLabel.textColor=[UIColor colorWithRed:(51/255.0) green:(51/255.0) blue:(51/255.0) alpha:1.0];
    
    //sliderButton
    sliderButton=[UIButton buttonWithType:UIButtonTypeCustom];
    sliderButton.frame=CGRectMake(84, 0, 152, 28);
    [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, 418) 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];
  
    // No Classes Scheduled label
    noClasses = [[UILabel alloc] initWithFrame:CGRectMake(80,160,200,30)];
    noClasses.text=@"No classes scheduled";
    noClasses.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 performSelector:@selector(dayChanged:) withObject:0];
    [self.view addSubview:tab];




}

-(void) getClasses 
{
    [parser parseXML:date withRoom:room];
    previousCourses= [parser getPreviousClasses];
    nextCourses= [parser getFollowingClasses];
    slide=NO;
}
// 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, 96);  //frame of the cell
    NSString *imageName=@"list_item_next.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
    

        }
        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
            if (currentDay==0)
                imageName=@"list_item_active.png";
        }

    }
    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];
            if (currentDay==0)
                imageName=@"list_item_active.png";
    }
    
    [cell setFields:frame withImage:imageName withId:course.idCourse withTitle:course.title withTeacher:course.teacher withHours:[NSString stringWithFormat:@"%@-%@",course.starthour,course.endhour]];  //set cell's properties
    return cell;
}

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

// 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, 50)];
    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 50;
        return 0;
    }
    return 50; //next section only

}


//when sliderButton is pressed
-(void) slide:(id) sender
{
    if ([previousCourses count] >0) {
        if (slide==YES) //if both of the sections are displayed, animate the previous section offscreen
            [coursesTable setContentOffset:CGPointMake(0, [previousCourses count]*96) 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]*96);  //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
{
    Course *course;
    int row=indexPath.row; //current row
    int section=indexPath.section; //current section
    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];
    else 
            course=[nextCourses objectAtIndex:row]; //current course
    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]*96-coursesTable.contentOffset.y+14); //slide the sliderButton at the same time with the table view
      dateLabel.center=CGPointMake(dateLabel.center.x,[previousCourses count]*96-coursesTable.contentOffset.y+42.5);
    }
   else
       dateLabel.center=CGPointMake(dateLabel.center.x,-coursesTable.contentOffset.y+42.5); 
}

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

-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    NSLog(@"%f",sliderButton.center.y);
    NSLog(@"%f",dateLabel.frame.origin.y);
    if (sliderButton.center.y==14)  // 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 reloadData];
        /*   [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  
{
    currentDay+=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
    [self getClasses];
    dateLabel.text=[formatter stringFromDate:date];
    dateLabel.center=CGPointMake(dateLabel.center.x,42.5);
    if ([previousCourses count] + [nextCourses count] > 0)  // if there are any classes to display
    {
        [noClasses removeFromSuperview];  //remmove noClasses label from view
        [self.view addSubview:coursesTable]; // add coursesTabke
        [self.view addSubview:dateLabel]; //add the current day label
        if (currentDay==0) {   // if we have chosen the current day
            sliderButton.center=CGPointMake(160, 14);
            [self.view addSubview:sliderButton];   // add the slider button
     /*       sliderButton.center=CGPointMake(sliderButton.center.x,-100);   // animate the slider button at the same time with the table view
            CGPoint offset=coursesTable.contentOffset;  //get the current offset (in this case 0)  */
            [coursesTable reloadData]; // reload data and animate the courses table on screen
   /*         coursesTable.contentOffset=CGPointMake(offset.x, offset.y+[nextCourses count]*100);  
            [UIView animateWithDuration:0.7 animations:^{coursesTable.contentOffset=offset;}]; //animate the courses and the slider button onscreen after reloading data 
            [UIView animateWithDuration:0.7 animations:^{sliderButton.center=CGPointMake(sliderButton.center.x,11.5);}]; */

        }
       
        else {  // we are either on a previos day or on a next day
            [sliderButton removeFromSuperview]; // remove slider  button
        //    CGPoint offset=coursesTable.contentOffset;  //get the current offset (in this case is 0)
            [coursesTable reloadData];  // reload data and animate the courses table on screen
     /*       coursesTable.contentOffset=CGPointMake(offset.x, offset.y+[nextCourses count]*100);  //keep previous section offscreen while reloading data
            [UIView animateWithDuration:0.7 animations:^{coursesTable.contentOffset=offset;}]; //slide previous courses onscreen after reloading data */
        }
      [self.view sendSubviewToBack:sliderButton];  
      [self.view sendSubviewToBack:dateLabel];
      [self.view sendSubviewToBack:coursesTable];
    }
    else { // no classes scheduled for the chosen date
        [coursesTable removeFromSuperview];
      //  [dateLabel removeFromSuperview];
        [sliderButton removeFromSuperview];
        [self.view addSubview:noClasses];
    }
}



@end
