//
// BusSearchReviewDetailViewController.m
// Project
//
// Created by Ziv on 16/4/29.
//
//

#import "BusVendorReviewDetailViewController.h"
#import "Lang.h"
#import "SDK.h"
#import "CocoaUtils.h"
#import "ContactsManager.h"
#import "DrawUtils.h"
#import "ImageUtils.h"
#import "UIConstants.h"
#import "TextViewController.h"
#import <HCSStarRatingView/HCSStarRatingView.h>
#import <IQKeyboardManager/IQTextView.h>
#import <PureLayout/PureLayout.h>
#import "Utility.h"
#import "BusVendorReview.h"
#import "Vars.h"


@interface BusVendorReviewDetailViewController ()

@property (nonatomic, weak) IBOutlet HCSStarRatingView  *busCleanlinessStarRatingView;
@property (nonatomic, weak) IBOutlet HCSStarRatingView  *punctualityStarRatingView;
@property (nonatomic, weak) IBOutlet HCSStarRatingView  *driverStaffStarRatingView;
@property (nonatomic, weak) IBOutlet HCSStarRatingView  *busComfortAmenitiesStarRatingView;

@property (nonatomic, weak) IBOutlet UITextField *firstNameField;
@property (nonatomic, weak) IBOutlet UITextField *lastNameField;
@property (nonatomic, weak) IBOutlet IQTextView *contentTextView;
@property (nonatomic, weak) IBOutlet UIButton *postButton;

@property (nonatomic, assign, readonly) NSInteger busCleanlinessRating;
@property (nonatomic, assign, readonly) NSInteger punctualityRating;
@property (nonatomic, assign, readonly) NSInteger driverStaffRating;
@property (nonatomic, assign, readonly) NSInteger busComfortAmenitiesRating;
@property (nonatomic, strong, readonly) NSString *firstName;
@property (nonatomic, strong, readonly) NSString *lastName;
@property (nonatomic, strong, readonly) NSString *comment;

@end

@implementation BusVendorReviewDetailViewController

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

- (void)viewDidLoad {
	[super viewDidLoad];

	self.firstNameField.placeholder = IMLocalizedString(@"First Name");
	self.firstNameField.im_textContentType = IMTextContentTypeGivenName;
	[CocoaUtils addKeyboardToolbarForTextField:self.firstNameField title:IMLocalizedString(@"Open Contacts") handler:^{
		[CocoaUtils showSelectionOfContactWithDisplayedPropertyKeys:@[CMContactGivenNameKey, CMContactFamilyNameKey] completion:^(CMContact *contact) {
			self.firstNameField.text = contact.givenName;
			self.lastNameField.text = contact.familyName;
		}];
	}];

	self.lastNameField.placeholder = IMLocalizedString(@"Last Name");
	self.lastNameField.im_textContentType = IMTextContentTypeFamilyName;
	[CocoaUtils addKeyboardToolbarForTextField:self.lastNameField title:IMLocalizedString(@"Open Contacts") handler:^{
		[CocoaUtils showSelectionOfContactWithDisplayedPropertyKeys:@[CMContactGivenNameKey, CMContactFamilyNameKey] completion:^(CMContact *contact) {
			self.firstNameField.text = contact.givenName;
			self.lastNameField.text = contact.familyName;
		}];
	}];

	[self initStarRating];

	self.contentTextView.placeholder = IMLocalizedString(@"Comments");
	[Utility addRoundedBorderToTextView:self.contentTextView];

	self.postButton.backgroundColor = [Vars defaultTintColor];
	[self.postButton setTitle:IMLocalizedString(@"Post Review") forState:UIControlStateNormal];
	[Utility addRoundedBorderToButton:self.postButton];
}

#pragma mark - Public

+ (NSAttributedString *)attributedFinishTextWithOverallRating:(CGFloat)overallRating byVendorName:(NSString *)vendorName {
	UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
	UIFont *boldFont = [CocoaUtils renderedFont:font withSymbolicTraits:UIFontDescriptorTraitBold];

	HCSStarRatingView *starRatingView = [[HCSStarRatingView alloc] initWithFrame:CGRectMake(0, 0, font.pointSize * 5.5, font.pointSize)];
	[CocoaUtils configureStarRatingView:starRatingView editing:NO];
	starRatingView.tintColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
	starRatingView.value = overallRating;
	UIImage *snapshotImage = [ImageUtils snapshotImageWithView:starRatingView];

	NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"Thank you for sharing your experience regarding your recent travel experience with %@!", vendorName] attributes:@{ NSFontAttributeName : font }]];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n\n"]];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"Your overall rating: " attributes:@{ NSFontAttributeName : font }]];
	[attributedString appendAttributedString:[CocoaUtils attributedStringForImage:snapshotImage verticalAlignWithFont:font]];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n\n"]];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"You have earned 100 " attributes:@{ NSFontAttributeName : font }]];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"GotoBus Loyalty Points!" attributes:@{ NSFontAttributeName : boldFont }]];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:@"\n\n"]];
	[attributedString appendAttributedString:[[NSAttributedString alloc] im_initWithString:[NSString stringWithFormat:@"Your feedback will help ys to evaluate the service provided by %@, and help them to identify areas where they can improve.", vendorName] attributes:@{ NSFontAttributeName : font }]];
	return [[NSAttributedString alloc] initWithAttributedString:attributedString];
}

#pragma mark - Segue

- (void)performSegueForReviewFinish {
	TextViewController *viewController = [[TextViewController alloc] init];
	viewController.title = @"Share your experience";
	[[Vars appDelegate] applyDefaultConfigurationForViewController:viewController];
	viewController.textView.attributedText = [BusVendorReviewDetailViewController attributedFinishTextWithOverallRating:self.entry.review_overall_rating byVendorName:self.entry.product.vendor_obj.short_name];
	[self.navigationController pushViewController:viewController animated:YES];
	NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
	[viewControllers removeObject:self];
	self.navigationController.viewControllers = viewControllers;
}

#pragma mark - Network

- (void)postBusVendorReview {
	BusVendorReview *reviewDetails = [[BusVendorReview alloc] init];
	reviewDetails.cleanliness_rating = self.busCleanlinessRating;
	reviewDetails.punctuality_rating = self.punctualityRating;
	reviewDetails.service_rating = self.driverStaffRating;
	reviewDetails.comfort_rating = self.busComfortAmenitiesRating;
	reviewDetails.content = self.comment;
	reviewDetails.first_name = self.firstName;
	reviewDetails.last_name = self.lastName;
	reviewDetails.recommend = YES;

	PostBusVendorReview *postReview = [[PostBusVendorReview alloc] init];
	postReview.entryId = self.entry.entry_id;
	postReview.reviewDetails = reviewDetails;

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

	[Utility getXMLFromRequestWithMethod:@"POST" url:postReview.address parameters:requestDict success:^(NSString *xml) {
		NSString *responseStr = xml;

		WebServiceResponseJsonMapper *mapper = [[WebServiceResponseJsonMapper alloc] initWithClass:[PostBusVendorReviewResponse class]];
		NSDictionary *jsonDict = [Utility JSONObjectWithXMLString:responseStr objectMapping:mapper.objectMapping];
		if (![mapper parseWithJSONObject:jsonDict]) {
			PostBusVendorReviewResponse *response = mapper.response;
			if (response.error_code > 0) {
				[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Error") message:response.error_message];
			} else if (response.overall_rating > 0) {
				self.entry.review_overall_rating = response.overall_rating;
				[self performSegueForReviewFinish];
			}
		}
	}];
}

#pragma mark - Action

- (IBAction)postReview:(UIButton *)sender {
	if (![self validateReview]) {
		return;
	}
	[self postBusVendorReview];
}

#pragma mark - Property

- (NSInteger)busCleanlinessRating {
	return self.busCleanlinessStarRatingView.value;
}

- (NSInteger)punctualityRating {
	return self.punctualityStarRatingView.value;
}

- (NSInteger)driverStaffRating {
	return self.driverStaffStarRatingView.value;
}

- (NSInteger)busComfortAmenitiesRating {
	return self.busComfortAmenitiesStarRatingView.value;
}

- (NSString *)firstName {
	return self.firstNameField.text;
}

- (NSString *)lastName {
	return self.lastNameField.text;
}

- (NSString *)comment {
	return self.contentTextView.text;
}

#pragma mark - Private

- (void)initStarRating {
	NSArray *subviews = @[self.busCleanlinessStarRatingView, self.punctualityStarRatingView, self.driverStaffStarRatingView, self.busComfortAmenitiesStarRatingView];
	for (HCSStarRatingView *wrapper in subviews) {
		[CocoaUtils configureStarRatingView:wrapper editing:YES];
		wrapper.tintColor = [CocoaUtils colorWithRGBs:StandardColorOrange];
	}
}

- (BOOL)validateReview {
	[self.scrollView endEditing:YES];
	for (UITextField *textField in @[self.firstNameField]) {
		if ([StringUtils isBlank:textField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:[NSString stringWithFormat:IMLocalizedString(@"Please fill out %@"), textField.placeholder.lowercaseString] dismissalHandler:^{
				[textField becomeFirstResponder];
			}];
			return NO;
		}
	}
	for (UITextField *textField in @[self.firstNameField, self.lastNameField]) {
		if (![Utility canBeConvertedToUrlEncodedFromString:textField.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
				[textField becomeFirstResponder];
			}];
			return NO;
		}
	}
	for (UITextView *textView in @[self.contentTextView]) {
		if (![Utility canBeConvertedToUrlEncodedFromString:textView.text]) {
			[CocoaUtils showAlertWithTitle:IMLocalizedString(@"Information") message:IMLocalizedString(@"Please enter alphabetic characters only") dismissalHandler:^{
				[textView becomeFirstResponder];
			}];
			return NO;
		}
	}
	return YES;
}

@end
