//
//  MessageSetViewController.m
//  Project
//
//  Created by 包光清 on 2019/1/10.
//

#import "MessageSetViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "UIConstants.h"
#import "NotificationApi.h"
#import "BeanUtils.h"
#import "NotifiCationSetting.h"
#import "DTAttributedTextCell.h"
#import <libextobjc/EXTScope.h>
#import "UserNotificationsManager.h"
#import "CocoaUtils.h"
#import "Utility.h"
#import "DrawUtils.h"
#import "UIToolkit.h"
#import "UIConstants.h"
#import "AppLocalConfig.h"
#import "Vars.h"

@interface MessageSetViewController ()
@property (nonatomic, strong) NSArray *cellDataArrays;
@property (nonatomic, strong) NSMutableArray *settingsListArray;
@property (nonatomic, assign) BOOL isNotificaionEnable;

@end

@implementation MessageSetViewController


- (instancetype)init {
	if (self = [super init]) {
		self.title = IMLocalizedString(@"Notification History");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
	[self.tableView setBackgroundColor:[UIColor groupTableViewBackgroundColor]];

	if (![Vars appDelegate].loginUser.is_support) {
		[self getUserNotifactionSetting];
	}
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(perfromNotificationForApplicationDidBecomeActive)
							   name:UIApplicationDidBecomeActiveNotification object:nil];
}

-(void)viewDidAppear:(BOOL)animated{
	[super viewDidAppear:animated];
	[self changeUserNotificationsFlag];
}

#pragma mark - network
- (void)changeSettingWithSetting:(NotifiCationSetting *)setting{
	UpdateUserNotificationSetting *updateUserMessagesset = [[UpdateUserNotificationSetting alloc] init];
	updateUserMessagesset.notificationTemplateId = setting.notificationTemplateId;
	updateUserMessagesset.disabled = setting.disabled == 0 ? 1 : 0;
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:updateUserMessagesset];
	
	[Utility performRESTRequestWithMethod:@"POST" url:updateUserMessagesset.address parameters:requestDict success:^(id jsonObject) {
		UpdateUserNotificationSettingResponse *response = [UpdateUserNotificationSettingResponse yy_modelWithJSON:jsonObject];
		if ([StringUtils isEmpty:response.errorMessage]) {
			setting.disabled = 	setting.disabled == 0 ? 1 : 0;
			[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:2] withRowAnimation:UITableViewRowAnimationNone];
		}else{
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:response.errorMessage];
		}
	}];
}

-(void)getUserNotifactionSetting {
	GetUserNotificationSettings *getUserMessagesset = [[GetUserNotificationSettings alloc] init];
	getUserMessagesset.userId = [Vars appDelegate].loginUser.uid;
	NSDictionary *requestDict = [BeanUtils describeAccessibleSimple:getUserMessagesset];
	
	[Utility performRESTRequestWithMethod:@"POST" url:getUserMessagesset.address parameters:requestDict success:^(id jsonObject) {
		GetUserNotificationSettingsResponse *response = [GetUserNotificationSettingsResponse yy_modelWithJSON:jsonObject];
		if (![StringUtils isEmpty:response.errorMessage]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error")  message:response.errorMessage];
			return ;
		}
		[self.settingsListArray addObjectsFromArray: response.settings];
		if (self.settingsListArray.count!= 0){
			[self buildCellDataSource];
		}
	}];
}

#pragma mark - private

- (void)buildCellDataSource {
	@weakify(self)
	NSMutableArray *arrays = [NSMutableArray array];
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.style = UITableViewCellStyleValue1;
			data.image = [DrawUtils tableViewCellImageWithFAKIcon:[FAKFontAwesome bellIconWithSize:24] fillColor:[UIColor lightGrayColor]];
			data.text = IMLocalizedString(@"New Message Notification");
			data.detailText = self.isNotificaionEnable ? @"YES" : @"NO";
			[data setDidSelectBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data) {
				if (UIApplicationOpenSettingsURLString != NULL) {
					UIApplication *application = [UIApplication sharedApplication];
					NSURL *URL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
					if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
						[application openURL:URL options:@{} completionHandler:nil];
					} else {
						[application openURL:URL];
					}
				}
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (YES) {
		NSMutableArray *array = [NSMutableArray array];
		if (YES) {
			TableViewCellData *data = [[TableViewCellData alloc] init];
			data.reuseIdentifier = NSStringFromClass([DTAttributedTextCell class]);
			data.backgroundColor = [UIColor clearColor];
			data.isCustomRegistered = YES;
			data.className = NSStringFromClass([DTAttributedTextCell class]);
			[data setPostInstallBlock:^(UITableView *tableView, NSIndexPath *indexPath, TableViewCellData *data, DTAttributedTextCell *cell) {
				cell.backgroundColor = [UIColor groupTableViewBackgroundColor];
				cell.contentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
				cell.attributedTextContextView.backgroundColor = [UIColor groupTableViewBackgroundColor];
				cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(5, 20 , 20, 15);
				[cell setHTMLString:IMLocalizedString(@"You can change under your device's system settings.") options:[self optionsForDisplayingHTMLString]];
				[CocoaUtils hideSeparatorOfCell:cell];
			}];
			[array addObject:data];
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	if (self.isNotificaionEnable && ![Vars appDelegate].loginUser.is_support) {
		NSMutableArray *array = [NSMutableArray array];
		for (NotifiCationSetting *setting in self.settingsListArray) {
			if (YES) {
				TableViewCellData *data = [[TableViewCellData alloc] init];
				data.style = UITableViewCellStyleValue1;
				data.text = setting.notificationTemplateName;
				data.editingType = TableViewCellEditingTypeSwitch;
				[data setValueObservingGetterBlock:^id {
					return @(!setting.disabled);
				}];
				[data setValueChangedPostActionBlock:^(UITableView *tzableView, NSIndexPath *indexPath, TableViewCellData *data, id editingControl) {
					@strongify(self)
					[self changeSettingWithSetting:setting];
				}];
				[array addObject:data];
			}
		}
		[arrays addObject:[NSArray arrayWithArray:array]];
	}
	self.cellDataArrays = arrays;
	[self.tableView reloadData];
}

- (NSDictionary *)optionsForDisplayingHTMLString {
	UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleFootnote];
	return @{ DTUseiOS6Attributes : @YES, DTDefaultFontFamily : font.familyName, DTDefaultFontSize : @(font.pointSize), DTDefaultLinkDecoration : @NO };
}


- (void)changeUserNotificationsFlag {
	[self buildCellDataSource];
	[[UIApplication sharedApplication] registerForRemoteNotifications];
}

- (void)perfromNotificationForApplicationDidBecomeActive {
	dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.5 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
		[self changeUserNotificationsFlag];
	});
}

#pragma mark - property
-(NSMutableArray *)settingsListArray{
	if (!_settingsListArray) {
		_settingsListArray = [NSMutableArray array];
	}
	return  _settingsListArray;
}

-(BOOL)isNotificaionEnable{
	return  [UserNotificationsManager authorizeUserNotifications];
}

#pragma mark - Table view methods

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
	if (section == 0) {
		return  @" ";
	} else if (section == 1) {
		
	} else if (section == 2) {
			return  @" ";
	}
	return nil;
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return [self.cellDataArrays[section] count];
}

- (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)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
	UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
	header.contentView.backgroundColor = [UIColor groupTableViewBackgroundColor];
	
}

-(void)dealloc{
	[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

@end
