//
//  MVMCoreUITopAlertMainView.m
//  mobilefirst
//
//  Created by Scott Pfeil on 8/17/16.
//  Copyright © 2016 Verizon Wireless. All rights reserved.
//

#import "MVMCoreUITopAlertMainView.h"
#import "MFStyler.h"
#import "NSLayoutConstraint+MFConvenience.h"
#import <MVMCore/NSDictionary+MFConvenience.h>
#import <MVMCore/MVMCoreDispatchUtility.h>
#import <MVMCoreUI/MVMCoreTopAlertObject.h>
#import "UIColor+MFConvenience.h"
#import <MVMCoreUI/MVMCoreAlertHandler.h>
#import <MVMCoreUI/MVMCoreUI-Swift.h>
#import <MVMCore/MVMCoreJSONConstants.h>
#import "MVMCoreUICommonViewsUtility.h"
#import "MVMCoreUITopAlertView.h"
#import <MVMCoreUI/MVMCoreUI-Swift.h>

@interface MVMCoreUITopAlertMainView ()

@property (nullable, strong, nonatomic) NSLayoutConstraint *labelRightConstraint;

@property (nullable, weak, nonatomic) UIView *centerView;
@property (nullable, weak, nonatomic) LoadImageView *iconView;
@property (nullable, weak, nonatomic) LoadImageView *topIconView;
@property (nullable, weak, nonatomic) Button *closeButton;
@property (nullable, strong, nonatomic) NSString *message;
@property (nullable, strong, nonatomic) NSString *subMessage;
@property (nullable, strong, nonatomic) UIColor *contentColor;

@end

@implementation MVMCoreUITopAlertMainView

- (void)handleAccessibility {
    UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, self.label);
}

#pragma mark - Setup View

- (void)updateView:(CGFloat)size {
    [super updateView:size];
    self.label.attributedText = [MVMCoreUITopAlertBaseView getStringForMessage:self.message subMessage:self.subMessage color:self.contentColor];
    self.label.accessibilityLabel = self.label.text;
    [MVMCoreUITopAlertBaseView amendAccesibilityLabelForView:self.label];
    [self.button updateView:size];
}

- (nullable instancetype)init {
    if (self = [super init]) {
        self.translatesAutoresizingMaskIntoConstraints = NO;
        self.clipsToBounds = YES;
        self.height = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:96];
        self.height.active = YES;
    }
    return self;
}

- (nullable instancetype)initWithTopAlertObject:(nonnull MVMCoreTopAlertObject *)topAlertObject animationDelegate:(nullable id <MVMCoreTopAlertAnimationDelegateProtocol>)animationDelegate {
    if (self = [self init]) {
        UIColor *contentColor = topAlertObject.textColor ?: [[MVMCoreUITopAlertView sharedGlobal] getContentColorForType:topAlertObject.type];
        self.backgroundColor = topAlertObject.backgroundColor ?: [[MVMCoreUITopAlertView sharedGlobal] getBackgroundColorForType:topAlertObject.type];
        [self setupViewWithLabelAndImage:topAlertObject.imageNameOrURL topImage:topAlertObject.aboveTextImageString];
        [self setupCloseButton:topAlertObject.useCloseButton animationDelegate:animationDelegate];
        [self setupWithMessage:topAlertObject.title subMessage:topAlertObject.message color:contentColor actionMap:topAlertObject.buttonMap additionalData:topAlertObject.additionalData];
    }
    return self;
}

- (nullable instancetype)initWithColor:(nonnull UIColor *)color contentColor:(nullable UIColor *)contentColor message:(nullable NSString *)message subMessage:(nullable NSString *)subMessage actionMap:(nullable NSDictionary *)actionMap additionalData:(nullable NSDictionary *)additionalData closeButton:(BOOL)closeButton animationDelegate:(nullable id <MVMCoreTopAlertAnimationDelegateProtocol>)animationDelegate {
    
    // Handles all scenarios.
    if (self = [self init]) {
        self.backgroundColor = color;
        [self setupViewWithLabelAndImage:nil topImage:nil];
        [self setupCloseButton:closeButton animationDelegate:animationDelegate];
        [self setupWithMessage:message subMessage:subMessage color:contentColor actionMap:actionMap additionalData:additionalData];
    }
    return self;
}

#pragma mark - inits with images

- (nullable instancetype)initWithColor:(nonnull UIColor *)color contentColor:(nullable UIColor *)contentColor imageURL:(nullable NSString *)imageURL message:(nullable NSString *)message subMessage:(nullable NSString *)subMessage actionMap:(nullable NSDictionary *)actionMap additionalData:(nullable NSDictionary *)additionalData closeButton:(BOOL)closeButton animationDelegate:(nullable id <MVMCoreTopAlertAnimationDelegateProtocol>)animationDelegate {
    
    // Handles all scenarios.
    if (self = [self init]) {
        self.backgroundColor = color;
        [self setupViewWithLabelAndImage:imageURL topImage:nil];
        [self setupCloseButton:closeButton animationDelegate:animationDelegate];
        [self setupWithMessage:message subMessage:subMessage color:contentColor actionMap:actionMap additionalData:additionalData];
    }
    return self;
}

- (nullable instancetype)initWithColor:(nonnull UIColor *)color contentColor:(nullable UIColor *)contentColor imageURL:(nullable NSString *)imageURL message:(nullable NSString *)message subMessage:(nullable NSString *)subMessage closeButton:(BOOL)closeButton animationDelegate:(nullable id <MVMCoreTopAlertAnimationDelegateProtocol>)animationDelegate {
    
    // No main button.
    if (self = [self init]) {
        self.backgroundColor = color;
        [self setupViewWithLabelAndImage:imageURL topImage:nil];
        [self setupCloseButton:closeButton animationDelegate:animationDelegate];
        [self setupWithMessage:message subMessage:subMessage color:contentColor buttonTitle:nil userActionHandler:NULL];
    }
    return self;
}

#pragma mark - setup

- (void)defaultSetup {
    if (!self.label) {
        self.translatesAutoresizingMaskIntoConstraints = NO;
        self.clipsToBounds = YES;
        self.height = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1 constant:96];
        self.height.active = YES;
        [self setupViewWithLabelAndImage:nil topImage:nil];
    }
}

- (void)setupViewWithLabelAndImage:(NSString *)imageURL topImage:(NSString *)topImageString {
    
    UIView *centerView = [MVMCoreUICommonViewsUtility commonView];
    [self addSubview:centerView];
    self.centerView = centerView;
    [centerView.centerYAnchor constraintEqualToAnchor:self.centerYAnchor].active = YES;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|->=0-[centerView]->=0-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(centerView)]];

    // Add the label.
    UILabel *label = self.label;
    if (label) {
        [label removeFromSuperview];
    } else {
        label = [MVMCoreUITopAlertBaseView topAlertLabel];
        self.label = label;
    }
    [centerView addSubview:label];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[label]-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:nil views:NSDictionaryOfVariableBindings(label)]];
    [label setContentHuggingPriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
    
    // Add Top Image
    if (self.topIconView) {
        [self.topIconView removeFromSuperview];
    }
    if (topImageString) {
        LoadImageView *imageView = [[LoadImageView alloc] initWithPinnedEdges:UIRectEdgeLeft | UIRectEdgeTop | UIRectEdgeBottom];
        imageView.imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.addSizeConstraintsForAspectRatio = YES;
        imageView.translatesAutoresizingMaskIntoConstraints = NO;
        [centerView addSubview:imageView];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-out-[imageView]-between-[label]-out-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:@{@"out":@(PaddingTwo),@"between":@(PaddingOne)} views:NSDictionaryOfVariableBindings(imageView,label)]];
        [imageView.leftAnchor constraintEqualToAnchor:label.leftAnchor].active = YES;
        [imageView.rightAnchor constraintEqualToAnchor:label.rightAnchor].active = YES;
        [imageView loadImageWithName:topImageString height:@(12)];
    } else {
        [NSLayoutConstraint constraintPinSubview:label pinTop:YES topConstant:PaddingTwo pinBottom:YES bottomConstant:PaddingTwo pinLeft:NO leftConstant:0 pinRight:NO rightConstant:0];
    }
    
    // Add main image.
    if (self.iconView) {
        [self.iconView removeFromSuperview];
    }
    
    CGFloat horizontalPadding = [MFStyler defaultHorizontalPaddingForApplicationWidth];
    if (imageURL) {
        LoadImageView *imageView = [[LoadImageView alloc] init];
        imageView.translatesAutoresizingMaskIntoConstraints = NO;
        [imageView setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
        [self addSubview:imageView];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|->=space-[imageView]->=space-|" options:NSLayoutFormatDirectionLeadingToTrailing metrics:@{@"space":@(PaddingFive)} views:NSDictionaryOfVariableBindings(imageView)]];
        [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-space-[imageView]-space-[centerView]" options:NSLayoutFormatDirectionLeadingToTrailing metrics:@{@"space":@(horizontalPadding)} views:NSDictionaryOfVariableBindings(imageView,centerView)]];
        [NSLayoutConstraint constraintWithItem:imageView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0].active = YES;
        self.iconView = imageView;
        [imageView loadImageWithName:imageURL width:@(32)];
    } else {
        [NSLayoutConstraint constraintWithItem:centerView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeLeft multiplier:1 constant:horizontalPadding].active = YES;
    }
}

- (void)setupCloseButton:(BOOL)closeButton animationDelegate:(nullable id <MVMCoreTopAlertAnimationDelegateProtocol>)animationDelegate {
    
    if (closeButton && !self.closeButton) {
        self.closeButton = [self addCloseButtonWithAnimationDelegate:animationDelegate];
        [self.closeButton setTintColor:self.contentColor ?: [UIColor whiteColor]];
    } else if (!closeButton && self.closeButton) {
        [self.closeButton removeFromSuperview];
        self.closeButton = nil;
    }
}

- (void)setupWithButton:(BOOL)showButton {
    
    // Setup the button.
    CGFloat horizontalPadding = [MFStyler defaultHorizontalPaddingForApplicationWidth];
    if (showButton) {
        
        if (!self.button) {
            
            // remove label right constraint
            self.labelRightConstraint.active = NO;

            // Sets up to use a button action. Always uses the top view controller
            PillButton *button = [[PillButton alloc] initAsPrimaryButton:false makeTiny:true];
            [button styleSecondary];
            [button setContentCompressionResistancePriority:UILayoutPriorityDefaultHigh forAxis:UILayoutConstraintAxisHorizontal];
            [button setContentHuggingPriority:800 forAxis:UILayoutConstraintAxisHorizontal];
            
            button.translatesAutoresizingMaskIntoConstraints = NO;
            [self addSubview:button];
            [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:self attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0].active = YES;
            [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.centerView attribute:NSLayoutAttributeRight multiplier:1 constant:PaddingThree].active = YES;
            [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:button attribute:NSLayoutAttributeRight multiplier:1 constant:(self.closeButton ? PaddingTen : horizontalPadding)].active = YES;
            self.button = button;
        }
    } else {
        
        // remove button.
        if (self.button) {
            [self.button removeFromSuperview];
            self.button = nil;
        }
        
        if (!self.labelRightConstraint) {
            self.labelRightConstraint = [NSLayoutConstraint constraintWithItem:self attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.centerView attribute:NSLayoutAttributeRight multiplier:1 constant:(self.closeButton ? PaddingTen : horizontalPadding)];
        }
        self.labelRightConstraint.active = YES;
    }
}


#pragma mark - Setters

- (void)setupWithMessage:(nullable NSString *)message subMessage:(nullable NSString *)subMessage color:(nullable UIColor *)color actionMap:(nullable NSDictionary *)actionMap additionalData:(nullable NSDictionary *)additionalData {
    self.message = message;
    self.subMessage = subMessage;
    self.contentColor = color;
    [MVMCoreDispatchUtility performBlockOnMainThread:^{
        
        // Sets the string
        self.label.attributedText = [MVMCoreUITopAlertBaseView getStringForMessage:message subMessage:subMessage color:color];
        self.label.accessibilityLabel = self.label.text;
        [MVMCoreUITopAlertBaseView amendAccesibilityLabelForView:self.label];
        
        // Sets the button
        [self setupButtonWithActionMap:actionMap additionalData:additionalData];
        if (color) {
            self.button.layer.borderColor = color.CGColor;
            [self.button setTitleColor:color forState:UIControlStateNormal];
            [self.closeButton setTintColor:color];
        }
    }];
}

- (void)setupWithMessage:(nullable NSString *)message subMessage:(nullable NSString *)subMessage color:(nullable UIColor *)color buttonTitle:(nullable NSString *)buttonTitle userActionHandler:(nullable void (^)(id  _Nonnull sender))userActionHandler {
    self.message = message;
    self.subMessage = subMessage;
    self.contentColor = color;
    [MVMCoreDispatchUtility performBlockOnMainThread:^{
        
        // Sets the string
        self.label.attributedText = [MVMCoreUITopAlertBaseView getStringForMessage:message subMessage:subMessage color:color];
        self.label.accessibilityLabel = self.label.text;
        [MVMCoreUITopAlertBaseView amendAccesibilityLabelForView:self.label];
        
        // Sets the color
        if (color) {
            self.button.layer.borderColor = color.CGColor;
            [self.button setTitleColor:color forState:UIControlStateNormal];
            [self.closeButton setTintColor:color];
        }
        
        // Sets the button
        [self setupButtonWithButtonTitle:buttonTitle userActionHandler:userActionHandler];
    }];
}

- (void)setupButtonWithActionMap:(nullable NSDictionary *)actionMap additionalData:(nullable NSDictionary *)additionalData {
    
    [MVMCoreDispatchUtility performBlockOnMainThread:^{
        BOOL showButton = actionMap != nil;
        [self setupWithButton:showButton];
        if (showButton) {
            [self.button setTitle:[actionMap stringForKey:KeyTitle] forState:UIControlStateNormal];
            self.button.accessibilityLabel = [self.button titleForState:UIControlStateNormal];
            [MVMCoreUITopAlertBaseView amendAccesibilityLabelForView:self.button];

            [MVMCoreUITopAlertBaseView addActionToButton:self.button actionMap:actionMap additionalData:additionalData];
        }
    }];
}

- (void)setupButtonWithButtonTitle:(nullable NSString *)buttonTitle userActionHandler:(nullable void (^)(id  _Nonnull sender))userActionHandler {
    
    [MVMCoreDispatchUtility performBlockOnMainThread:^{
        BOOL showButton = buttonTitle.length > 0;
        [self setupWithButton:showButton];
        [self.button setTitle:buttonTitle forState:UIControlStateNormal];
        self.button.accessibilityLabel = [self.button titleForState:UIControlStateNormal];
        [MVMCoreUITopAlertBaseView amendAccesibilityLabelForView:self.button];
        if (showButton && userActionHandler) {
            [self.button addActionBlockWithEvent:UIControlEventTouchUpInside :userActionHandler];
        }
    }];
}

#pragma mark - legacy inits

- (nullable instancetype)initWithColor:(nonnull UIColor *)color contentColor:(nonnull UIColor *)contentColor message:(nullable NSString *)message subMessage:(nullable NSString *)subMessage actionMap:(nullable NSDictionary *)actionMap additionalData:(nullable NSDictionary *)additionalData {
    
    // No icon or close button.
    if (self = [self init]) {
        self.backgroundColor = color;
        [self setupViewWithLabelAndImage:nil topImage:nil];
        [self setupWithMessage:message subMessage:subMessage color:contentColor actionMap:actionMap additionalData:additionalData];
    }
    return self;
}

- (nullable instancetype)initWithColor:(nonnull UIColor *)color contentColor:(nonnull UIColor *)contentColor message:(nullable NSString *)message subMessage:(nullable NSString *)subMessage closeButton:(BOOL)closeButton animationDelegate:(nullable id <MVMCoreTopAlertAnimationDelegateProtocol>)animationDelegate {
    
    // No main button.
    if (self = [self init]) {
        self.backgroundColor = color;
        [self setupViewWithLabelAndImage:nil topImage:nil];
        [self setupWithMessage:message subMessage:subMessage color:contentColor buttonTitle:nil userActionHandler:NULL];
        [self setupCloseButton:closeButton animationDelegate:animationDelegate];
    }
    return self;
}

- (nullable instancetype)initWithColor:(nonnull UIColor *)color contentColor:(nonnull UIColor *)contentColor message:(nullable NSString *)message subMessage:(nullable NSString *)subMessage buttonTitle:(nullable NSString *)buttonTitle userActionHandler:(nullable void (^)(id  _Nonnull sender))userActionHandler {
    
    // No icon or close button. Custom button action.
    if (self = [self init]) {
        self.backgroundColor = color;
        [self setupViewWithLabelAndImage:nil topImage:nil];
        [self setupWithMessage:message subMessage:subMessage color:contentColor buttonTitle:buttonTitle userActionHandler:userActionHandler];
    }
    return self;
}

@end
