#import "MailViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "DrawUtils.h"
#import "UIConstants.h"
#import "Validator.h"
#import <BlocksKit/BlocksKit+UIKit.h>
#import <libextobjc/EXTScope.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "PerlWS.h"
#import "Vars.h"


@interface MailViewController ()

@property (nonatomic, weak) IBOutlet UIView *emailView;
@property (nonatomic, weak) IBOutlet UILabel *emailLabel;
@property (nonatomic, weak) IBOutlet UITextField *emailTextField;
@property (nonatomic, weak) IBOutlet UIView *nameView;
@property (nonatomic, weak) IBOutlet UILabel *nameLabel;
@property (nonatomic, weak) IBOutlet UITextField *nameTextField;
@property (nonatomic, weak) IBOutlet UIView *subjectView;
@property (nonatomic, weak) IBOutlet UILabel *subjectLabel;
@property (nonatomic, weak) IBOutlet UITextField *subjectTextField;
@property (nonatomic, weak) IBOutlet UITextView *messageBodyTextView;
@property (nonatomic, weak) IBOutlet NSLayoutConstraint *subjectViewTopConstraint;

@end

@implementation MailViewController

- (instancetype)init {
	if (self = [super init]) {
		self.edgesForExtendedLayout = UIRectEdgeNone;
		// Custom initialization
		self.title = IMLocalizedString(@"Feedback");
		[[Vars appDelegate] applyDefaultConfigurationForViewController:self];
	}
	return self;
}

- (void)viewDidLoad {
	[super viewDidLoad];

	if (@available(iOS 11.0, *)) {
		self.messageBodyTextView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
	} else {
		self.automaticallyAdjustsScrollViewInsets = NO;
	}

	@weakify(self)
	self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] im_initWithBarButtonSystemItem:UIBarButtonSystemItemCancel handler:^(UIBarButtonItem *barButtonItem) {
		@strongify(self)
		[self.navigationController popViewControllerAnimated: YES];
	}];
	self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] im_initWithTitle:IMLocalizedString(@"Send") style:UIBarButtonItemStyleDone handler:^(UIBarButtonItem *barButtonItem) {
		@strongify(self)
		if ([self validateRequest]) {
			[self addRequest];
		}
	}];

	self.nameLabel.text = [StringUtils join:IMLocalizedString(@"Your Name"), IMLocalizedString(PUNCTUATION_COLON), nil];
	self.emailLabel.text = [StringUtils join:IMLocalizedString(@"Your Email"), IMLocalizedString(PUNCTUATION_COLON), nil];
	self.subjectLabel.text = [StringUtils join:IMLocalizedString(@"Subject"), IMLocalizedString(PUNCTUATION_COLON), nil];
	[self judgeLogin];
}

#pragma mark - Network

- (void)addRequest {
	AddRequest *addRequest = [[AddRequest alloc] init];
	addRequest.customer_email = self.emailTextField.text;
	addRequest.customer_name = self.nameTextField.text;
	addRequest.subject = self.subjectTextField.text;
	addRequest.message = self.messageBodyTextView.text;

	NSDictionary *requestDict = [Utility perlParamXml:[addRequest innerXML] action:addRequest.name];

	[Utility getXMLFromRequestWithMethod:@"POST" url:addRequest.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;
		// NSLog(@"%@", responseStr);
		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[AddRequestResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			AddRequestResponse *response = mapper.response;
			if (![StringUtils isEmpty:response.error]) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error];
			} else {
				if (response.status == 1) {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Send Success") dismissalHandler:^{
						[self.navigationController popViewControllerAnimated:YES];
					}];
				} else {
					[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:IMLocalizedString(@"Send Failed") dismissalHandler:^{
						[self.navigationController popViewControllerAnimated:YES];
					}];
				}
			}
		}
	}];
}

#pragma mark - Private

- (void)judgeLogin {
	if ([Vars appDelegate].loginUser) {
		self.nameView.hidden = YES;
		self.emailView.hidden = YES;
		self.subjectViewTopConstraint.active = NO;
		[self.subjectView autoPinEdgeToSuperviewEdge:ALEdgeTop withInset:0];
	}
}

- (BOOL)validateRequest {
	[self.view endEditing:YES];
	if (![Vars appDelegate].loginUser) {
		if ([StringUtils isBlank:self.emailTextField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), self.emailLabel.text.lowercaseString] dismissalHandler:^{
				[self.emailTextField becomeFirstResponder];
			}];
			return NO;
		}
		if (![GenericValidator isEmail:self.emailTextField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please check against out %@"), self.emailLabel.text.lowercaseString] dismissalHandler:^{
				[self.emailTextField becomeFirstResponder];
			}];
			return NO;
		}
		if ([StringUtils isBlank:self.nameTextField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), self.nameLabel.text.lowercaseString] dismissalHandler:^{
				[self.nameTextField becomeFirstResponder];
			}];
			return NO;
		}
		if (![Utility canBeConvertedToUrlEncodedFromString:self.nameTextField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
				[self.nameTextField becomeFirstResponder];
			}];
			return NO;
		}
	}
	if ([StringUtils isBlank:self.subjectTextField.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), self.subjectLabel.text.lowercaseString] dismissalHandler:^{
			[self.subjectTextField becomeFirstResponder];
		}];
		return NO;
	}
	if ([StringUtils isBlank:self.messageBodyTextView.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), self.title.lowercaseString] dismissalHandler:^{
			[self.messageBodyTextView becomeFirstResponder];
		}];
		return NO;
	}
	if (![Utility canBeConvertedToUrlEncodedFromString:self.subjectTextField.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
			[self.subjectTextField becomeFirstResponder];
		}];
		return NO;
	}
	if (![Utility canBeConvertedToUrlEncodedFromString:self.messageBodyTextView.text]) {
		[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
			[self.messageBodyTextView becomeFirstResponder];
		}];
	}
	return YES;
}

@end
