#import "TabBarViewController.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import <BlocksKit/BlocksKit.h>
#import <EAIntroView/EAIntroView.h>
#import "Utility.h"
#import "CustomIcons.h"
#import "BusSearchBoxViewController.h"
#import "SelfCheckInSearchViewController.h"
#import "ToolsViewController.h"
#import "TrackBusStatusViewController.h"
#import "PurchaseRecordViewController.h"
#import "Vars.h"
NSString *const TabBarItemHome = @"HomeViewController";
NSString *const TabBarItemMyAccount = @"ToolsViewController";

@interface TabBarViewController ()
@property (nonatomic, strong) NSString *targetSelectedViewControllerClassName;
@end

@implementation TabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter addObserver:self selector:@selector(didPerformSegue:) name:SegueDidPerformNotification object:nil];
    
    NSMutableArray *viewControllers = [NSMutableArray array];
    if (NSClassFromString(@"HomeViewController")) {
        UIViewController *viewController = [[NSClassFromString(@"HomeViewController") alloc] init];
        viewController.tabBarItem.title = @"Home";
        viewController.tabBarItem.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome homeIconWithSize:32] fillColor:[UIColor blackColor]];
        [viewControllers addObject:viewController];
    } else {
        BusSearchBoxViewController *viewController = [[BusSearchBoxViewController alloc] init];
        viewController.tabBarItem.title = @"Bus Tickets";
        viewController.tabBarItem.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome ticketIconWithSize:32] fillColor:[UIColor blackColor]];
        [viewControllers addObject:viewController];
    }
    [viewControllers addObjectsFromArray:[self majorChildViewControllers]];
    if (YES) {
        ToolsViewController *viewController = [[ToolsViewController alloc] init];
		viewController.tabBarItem.title = @"Account";
        viewController.tabBarItem.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome userIconWithSize:32] fillColor:[UIColor blackColor]];
        [viewControllers addObject:viewController];
    }
    
    [self setViewControllers:[viewControllers bk_map:^id (id obj) {
        return [CocoaUtils wrappingNavigationControllerAroundViewController:obj];
    }] animated:YES];
    self.selectedIndex = [self selectedIndexWithChildViewControllerClass:[self defaultChildViewControllerClass]];
    
//    if ([Vars clientDomainId] == 3838) {
//        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//        if (![userDefaults boolForKey:UserDefaultsKeyEAIntroViewSkipped]) {
//            [userDefaults setBool:YES forKey:UserDefaultsKeyEAIntroViewSkipped];
//            [self showIntroWithCustomView];
//        }
//    }
	
}

#pragma mark - Notification

- (void)didPerformSegue:(NSNotification *)notification {
    self.targetSelectedViewControllerClassName = notification.object ? notification.object : nil;
}

#pragma mark - Public

- (void)reloadTabBarIfNeeded:(BOOL)needed {
    if (needed) {
        NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.viewControllers];
        NSArray *majorViewControllers = [self majorChildViewControllers];
        [viewControllers removeObjectsInRange:NSMakeRange(1, viewControllers.count - 2)];
        [viewControllers insertObjects:[majorViewControllers bk_map:^id (id obj) {
            return [CocoaUtils wrappingNavigationControllerAroundViewController:obj];
        }] atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, majorViewControllers.count)]];
        [self setViewControllers:viewControllers animated:YES];
    }
    if (self.targetSelectedViewControllerClassName != nil) {
        self.selectedIndex = [self selectedIndexWithChildViewControllerClass:NSClassFromString(self.targetSelectedViewControllerClassName)];
        self.targetSelectedViewControllerClassName = nil;
    }
}

- (NSUInteger)selectedIndexWithChildViewControllerClass:(Class)klass {
    return [self.viewControllers indexOfObjectPassingTest:^BOOL (UINavigationController *obj, NSUInteger idx, BOOL *stop) {
        return *stop = (obj.viewControllers.count > 0 && [obj.viewControllers[0] isKindOfClass:klass]);
    }];
}

#pragma mark - Property

- (Class)defaultChildViewControllerClass {
    Class viewControllerClass = Nil;
    if ([Vars appDelegate].loginUser) {
        if ([Vars appDelegate].loginUser.is_support && NSClassFromString(@"SoldStockSearchViewController")) {
            viewControllerClass = NSClassFromString(@"SoldStockSearchViewController");
        } else if ([Vars appDelegate].loginUser.is_vendor && NSClassFromString(@"VendorDatePickController")) {
            viewControllerClass = NSClassFromString(@"VendorDatePickController");
        } else if ([Vars appDelegate].loginUser.is_bus_driver && NSClassFromString(@"ScheduleDriverSearchViewController")) {
            viewControllerClass = NSClassFromString(@"ScheduleDriverSearchViewController");
        }
        return viewControllerClass ? viewControllerClass : [ToolsViewController class];
    } else {
        viewControllerClass = NSClassFromString(@"HomeViewController");
        return viewControllerClass ? viewControllerClass : [BusSearchBoxViewController class];
    }
}

- (NSArray *)majorChildViewControllers {
	NSMutableArray *viewControllers = [NSMutableArray array];
	if (NSClassFromString(@"ExploreViewController")) {
		UIViewController *viewController = [[NSClassFromString(@"ExploreViewController") alloc] init];
		viewController.tabBarItem.title = @"Explore";
		viewController.tabBarItem.image = [ImageUtils scaleImage:[ImageUtils imageNamed:@"explore" tintColor:[UIColor blackColor]] toSize:CGSizeMake(28, 28)];
		[viewControllers addObject:viewController];
	}
	if ([Vars appDelegate].loginUser.is_support) {
		if (NSClassFromString(@"SoldStockSearchViewController")) {
			UIViewController *viewController = [[NSClassFromString(@"SoldStockSearchViewController") alloc] init];
			viewController.tabBarItem = [[UITabBarItem alloc] initWithTabBarSystemItem:UITabBarSystemItemSearch tag:@"SoldStockSearchViewController".hash];
			[viewControllers addObject:viewController];
		}
	} else if ([Vars appDelegate].loginUser.is_vendor) {
		if ([Vars appDelegate].loginUser.sell_bus || [Vars appDelegate].loginUser.sell_show) {
            if ( ![Vars appDelegate].loginUser.enable_stop_based_booking_report && ![Vars appDelegate].loginUser.enable_destination_based_booking_report) {
                if (NSClassFromString(@"CheckInSearchViewController")) {
                    UIViewController *viewController = [[NSClassFromString(@"CheckInSearchViewController") alloc] init];
                    viewController.tabBarItem.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome checkSquareOIconWithSize:30] fillColor:[UIColor blackColor]];
                    [viewControllers addObject:viewController];
                }
            }
		}
		if (NSClassFromString(@"VendorDatePickController")) {
			UIViewController *viewController = [[NSClassFromString(@"VendorDatePickController") alloc] init];
			viewController.tabBarItem.title = @"Booking Report";
			viewController.tabBarItem.image = [DrawUtils imageWithFAKIcon:[FAKIonIcons iosPaperIconWithSize:32] fillColor:[UIColor blackColor]];
			[viewControllers addObject:viewController];
		}
	} else if ([Vars appDelegate].loginUser.is_bus_driver) {
		if (NSClassFromString(@"ScheduleDriverSearchViewController")) {
			UIViewController *viewController = [[NSClassFromString(@"ScheduleDriverSearchViewController") alloc] init];
			viewController.tabBarItem.image = [DrawUtils imageWithFAKIcon:[CustomIcons driverIconWithSize:28] fillColor:[UIColor blackColor]];
			[viewControllers addObject:viewController];
		}
	} else {
		
		if (YES) {
			PurchaseRecordViewController *viewController = [[PurchaseRecordViewController alloc] init];
			viewController.tabBarItem.image = [DrawUtils imageWithFAKIcon:[FAKFontAwesome suitcaseIconWithSize:28] fillColor:[UIColor blackColor]];
			viewController.tabBarItem.title = @"My Trips";
			[viewControllers addObject:viewController];
		}
		if (YES) {
			if (NSClassFromString(@"LiveHelpViewController")) {
				UIViewController *viewController = [[NSClassFromString(@"LiveHelpViewController") alloc] init];
				viewController.tabBarItem.image = [ImageUtils imageNamed:@"inbox" tintColor:[UIColor blackColor]];
				viewController.tabBarItem.title = @"Support";
				[viewControllers addObject:viewController];
			}
		}
	}
	return [NSArray arrayWithArray:viewControllers];
}

#pragma mark - Private

- (void)showIntroWithCustomView {
    UIImageView *imageView1 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[Utility fullImageNameByLaunchSyntaxFromAsset:@"Intro-Page1"]]];
    EAIntroPage *page1 = [EAIntroPage pageWithCustomView:imageView1];
    UIImageView *imageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[Utility fullImageNameByLaunchSyntaxFromAsset:@"Intro-Page2"]]];
    EAIntroPage *page2 = [EAIntroPage pageWithCustomView:imageView2];
    UIImageView *imageView3 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[Utility fullImageNameByLaunchSyntaxFromAsset:@"Intro-Page3"]]];
    EAIntroPage *page3 = [EAIntroPage pageWithCustomView:imageView3];
    
    EAIntroView *intro = [[EAIntroView alloc] initWithFrame:[UIScreen mainScreen].bounds andPages:@[page1, page2, page3]];
    intro.backgroundColor = [UIColor whiteColor];
    intro.skipButton.hidden = YES;
    intro.pageControl.hidden = YES;
    [intro showInView:self.view animateDuration:0];
}

#pragma mark

- (void)dealloc {
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:SegueDidPerformNotification object:nil];
}

@end
