//
// MyAccountTableViewController.m
// IvyMedia
//
// Created by paul on 8/27/14.
//
//

#import "MyAccountViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "UserNotificationsManager.h"
#import "UIConstants.h"
#import "UIToolkit.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "PerlWS.h"
#import "UserHeaderView.h"
#import "AboutViewController.h"
#import "AddressListViewController.h"
#import "ChangePasswordViewController.h"
#import "CreditCardListViewController.h"
#import "LoginViewController.h"
#import "MessageListViewController.h"
#import "PurchaseRecordViewController.h"
#import "Vars.h"

NSString *const CalendarEventsCellIdentifier = @"CalendarEventsCellIdentifier";

@interface MyAccountViewController ()
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) UserHeaderView *headerView;
@property (nonatomic, strong) UIButton *messageButton;
@property (nonatomic, strong) UIView *headerBackGroundView;
@end

@implementation MyAccountViewController

- (instancetype)init {
	if (self = [super init]) {
		self.title = IMLocalizedString(@"My Account");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
	[notificationCenter addObserver:self selector:@selector(didChangeLoginStatus) name:LoginStatusDidChangeNotification object:nil];
	
	UIView *backGroundView = [[UIView alloc] initWithFrame: CGRectMake(0, 0, CGRectGetWidth(self.view.frame), self.tableView.contentOffset.y)];
	backGroundView.backgroundColor = [UIColor whiteColor];
	[self.view addSubview:backGroundView];
	self.headerBackGroundView = backGroundView;

	@weakify(self)
	UserHeaderView *headerView = [UserHeaderView viewFromNib];
	[headerView.loginButton bk_addEventHandler:^(id  _Nonnull sender) {
		@strongify(self)
		[self performSegueWithViewControllerClass:[LoginViewController class]];
	} forControlEvents:UIControlEventTouchUpInside];
	self.headerView = headerView;
	[self modifyHeaderView];
	self.tableView.tableHeaderView = headerView;

	self.tableView.sectionHeaderHeight = [UIConstants defaultTableViewCellLayoutInsets].top;
	self.tableView.sectionFooterHeight = [UIConstants defaultTableViewCellLayoutInsets].bottom;
	[self buildCellDataSource];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	
	if ([Vars appDelegate].loginUser) {
		[self changeCalendarEventsFlag];
	}
}

- (void)viewWillLayoutSubviews {
	[super viewWillLayoutSubviews];
	
	self.headerView.frame = CGRectMake(0, 0, CGRectGetWidth(self.tableView.frame), 70);
}

#pragma mark - Notification

- (void)didChangeLoginStatus {
	[self buildCellDataSource];
	[self.tableView reloadData];
	[self modifyHeaderView];
}

#pragma mark - Action

#pragma mark - Segue

- (void)performSegueForContactInfoManagement {
	AddressListViewController *viewController = [[AddressListViewController alloc] init];
	viewController.title = IMLocalizedString(@"My Contact Information");
    viewController.addressType = AddressTypeContactInfo;
	viewController.addresses = [Vars appDelegate].loginUser.contactInfos;
	viewController.allowsDefault = YES;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueForCreditCardManagement {
	CreditCardListViewController *viewController = [[CreditCardListViewController alloc] init];
	viewController.title = IMLocalizedString(@"My Credit Cards");
	viewController.creditCards = [Vars appDelegate].loginUser.creditCards;
	viewController.allowsDefault = YES;
	[self.navigationController pushViewController:viewController animated:YES];
}

- (void)performSegueWithViewControllerClass:(Class)class {
	UIViewController *viewController = [[class alloc] init];
	[self.navigationController pushViewController:viewController animated:YES];
}

#pragma mark - Private

- (void)buildCellDataSource {
    @weakify(self)
	NSMutableArray *arrays = [NSMutableArray array];
	if ([Vars appDelegate].loginUser) {
		[arrays addObject:@[]];
	}
	if ([Vars appDelegate].loginUser) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"My Contact Information");
			data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome addressCardOIconWithSize:20] fillColor:[UIColor lightGrayColor]];
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForContactInfoManagement];
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.text = IMLocalizedString(@"My Credit Cards");
			data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome creditCardIconWithSize:20] fillColor:[UIColor lightGrayColor]];
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueForCreditCardManagement];
			}];
			[array addObject:data];
		}
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome userSecretIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			data.text = IMLocalizedString(@"Change Password");
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				@strongify(self)
				[self performSegueWithViewControllerClass:[ChangePasswordViewController class]];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if ([Vars appDelegate].loginUser) {
		NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.identifier = CalendarEventsCellIdentifier;
			data.style = UITableViewCellStyleValue1;
			data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome calendarIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			data.text = IMLocalizedString(@"Add trips to my calendar");
			data.adjustsTextFontSize = YES;
			data.editingType = TableViewCellEditingTypeSwitch;
			[data setValueObservingGetterBlock:^id {
				return @([userDefaults boolForKey:UserDefaultsKeyCalendarEventsEnabled]);
			}];
			[data setValueObservingSetterBlock:^(id value) {
				[userDefaults setBool:[value boolValue] forKey:UserDefaultsKeyCalendarEventsEnabled];
			}];
			[data setValueChangedPostActionBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, id editingControl) {
				@strongify(self)
				[self changeCalendarEventsFlag];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		[arrays addObject:[NSArray arrayWithArray:[self addHelps]]];
	}
	if ([Vars appDelegate].loginUser) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome signOutIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			data.text = IMLocalizedString(@"Log out");
			data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				[[Vars appDelegate] logout];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = [NSArray arrayWithArray:arrays];
}

- (void)changeCalendarEventsFlag {
	NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
	if (![userDefaults boolForKey:UserDefaultsKeyCalendarEventsEnabled]) {
		return;
	}
	if ([Utility authorizeCalendarForEvents]) {
		return;
	}
	[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please allow \"%@\" to access your calendar"), [CocoaUtils bundleName]]];
	[userDefaults setBool:NO forKey:UserDefaultsKeyCalendarEventsEnabled];
	[self reloadTableViewCellByIdentifier:CalendarEventsCellIdentifier];
}


- (NSMutableArray *)addHelps {
	@weakify(self)
	NSMutableArray *array = [NSMutableArray array];
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.image = [ImageUtils scaleImage:[ImageUtils imageNamed:@"icon_language_setting" tintColor:[UIColor lightGrayColor]] toWidth:24];
		data.text = IMLocalizedString(@"Language Setting");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			[[Vars appDelegate] changeLanguage];
		}];
		[array addObject:data];
	}
	if (YES) {
		TableViewCellData *data = [[TableViewCellData alloc] init];
		data.image =  [ImageUtils scaleImage:[ImageUtils imageNamed:@"Icon-24h" tintColor:[UIColor lightGrayColor]] toWidth:24];
		data.text = IMLocalizedString(@"About Us");
		data.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
			@strongify(self)
			[self performSegueWithViewControllerClass:[AboutViewController class]];
		}];
		[array addObject:data];
	}
	return array;
}

- (void)reloadTableViewCellByIdentifier:(NSString *)cellIdentifier {
    NSIndexPath *indexPath = [CocoaUtils indexPathOfObjectIdenticalTo:[CocoaUtils objectPassingTest:^BOOL (TableViewCellData *obj, NSUInteger idx, BOOL *stop) {
        return [obj.identifier isEqualToString:cellIdentifier];
    } fromArrays:self.cellDataArrays] fromArrays:self.cellDataArrays];
    if (indexPath) {
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    }
}

-(void)modifyHeaderView{
	if ([Vars appDelegate].loginUser) {
		self.headerView.emailLabel.text = [Vars appDelegate].loginUser.email;
		self.headerView.emailLabel.hidden = NO;
		Address *address = [Address defaultOfAddresses:[Vars appDelegate].loginUser.contactInfos];
		if (address.first_name) {
			self.headerView.nameLabel.text = address.first_name;
			self.headerView.nameLabel.hidden = NO;
		}else{
			self.headerView.nameLabel.hidden = YES;
		}
		self.headerView.loginButton.hidden = YES;
         self.messageButton.hidden = NO;
	}else{
		self.headerView.emailLabel.hidden = YES;
		self.headerView.nameLabel.hidden = YES;
		self.headerView.loginButton.hidden = NO;
		self.messageButton.hidden = YES;
	}
}

#pragma mark - Table view methods

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if (section == 0) {
		if(![Vars appDelegate].loginUser){
			return IMLocalizedString(@"MORE");
		}
	} else if (section == 1) {
		return IMLocalizedString(@"MY PROFILE");
	} else if (section == 2) {
		return IMLocalizedString(@"SETTINGS");
	} else if (section == 3) {
		return IMLocalizedString(@"MORE");
	} else if (section == tableView.numberOfSections - 1) {
		return @" ";
	}
	return nil;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return self.cellDataArrays.count;
}

// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.cellDataArrays[section] count];
}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	return [UIToolkit tableView:tableView atIndexPath:indexPath cellWithData:data];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	[tableView deselectRowAtIndexPath:indexPath animated:YES];
	TableViewCellData *data = self.cellDataArrays[indexPath.section][indexPath.row];
	[UIToolkit tableView:tableView atIndexPath:indexPath didSelectWithData:data];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
	CGFloat offsetY = scrollView.contentOffset.y;
	if (offsetY <= 0) {
		self.headerBackGroundView.frame = CGRectMake(0, offsetY, CGRectGetWidth(self.view.frame), -offsetY);
	}
}

#pragma mark

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

@end
