//
//  MVMCoreUISession.m
//  MVMCoreUI
//
//  Created by Scott Pfeil on 1/10/19.
//  Copyright © 2019 Verizon Wireless. All rights reserved.
//

#import "MVMCoreUISession.h"
#import "MFLoadingViewController.h"
#import "NSLayoutConstraint+MFConvenience.h"
@import MVMCore.MVMCoreObject;

@interface MVMCoreUISession () <MVMCoreLoadingOverlayDelegateProtocol>

@property (weak, nonatomic, nullable) UIViewController *mainViewController;

@end

@implementation MVMCoreUISession

- (nullable UIView *)titleViewForController:(nonnull MFViewController *)controller {
    return nil;
}

- (void)setupAsStandardLoadViewDelegate:(nonnull UIViewController *)mainViewController {
    self.mainViewController = mainViewController;
    [MVMCoreObject sharedInstance].loadingProtocol = self;
}

#pragma mark - MVMCoreLoadingOverlayDelegateProtocol

- (nonnull UIViewController <MVMCoreLoadingViewControllerProtocol> *)getLoadingViewController {
    
    if (self.loadingViewController) {
        return self.loadingViewController;
    } else {
        MFLoadingViewController *loadingViewController = [[MFLoadingViewController alloc] init];
        UIView *view = loadingViewController.view;
        view.hidden = YES;
        self.loadingViewController = loadingViewController;
        
        // Adds the overlay to the screen.
        UIView *viewToPresentOn = self.mainViewController.view;
        [self.mainViewController addChildViewController:loadingViewController];
        [viewToPresentOn addSubview:view];
        [loadingViewController didMoveToParentViewController:self.mainViewController];
        
        // Sets the constraints for autolayout
        [view setTranslatesAutoresizingMaskIntoConstraints:NO];
        [NSLayoutConstraint constraintPinSubviewToSuperview:view];
        return loadingViewController;
    }
}

- (void)beginningLoading {
    // Disables the UI when loading
    self.mainViewController.view.userInteractionEnabled = NO;
}

- (void)finishedLoading {
    self.mainViewController.view.userInteractionEnabled = YES;
}

@end
