//
//  AuthorizationProgressViewController.m
//  HotPocket (macOS)
//
//  Created by Tomek Wójcik on 20/09/2025.
//

#import "AuthorizationProgressViewController.h"

#import "AppDelegate.h"
#import "AuthorizationViewController.h"
#import "HPCredentialsHelper.h"
#import "MainViewController.h"
#import "ReplaceAnimator.h"

@interface AuthorizationProgressViewController (AuthorizationProgressViewControllerPrivate)

#pragma mark - Private interface

@end

@implementation AuthorizationProgressViewController

#pragma mark - View lifecycle

-(void)viewDidLoad {
    [super viewDidLoad];
}

-(void)viewWillAppear {
    AppDelegate *appDelegate = [[NSApplication sharedApplication] delegate];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAuthFlowDidFinish:) name:@"AuthFlowDidFinish" object:appDelegate.authFlow];
    
    [self.progressIndicator startAnimation:self];
}

-(void)viewDidDisappear {
    [self.progressIndicator stopAnimation:self];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - Notification handlers

-(void)onAuthFlowDidFinish:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        HPCredentials *credentials = [[HPCredentialsHelper sharedHelper] getCredentials];
        
        [[NSApplication sharedApplication] requestUserAttention:NSInformationalRequest];
        [[NSApplication sharedApplication] activateIgnoringOtherApps:YES];
        
        if (credentials.usable == NO) {
            NSAlert *alert = [[NSAlert alloc] init];
            alert.alertStyle = NSAlertStyleCritical;
            alert.messageText = NSLocalizedString(@"Oops!", @"Oops!");
            alert.informativeText = NSLocalizedString(@"HotPocket couldn't complete this operation.", @"HotPocket couldn't complete this operation.");
            [alert runModal];
            
            AuthorizationViewController *authorizationViewController = [self.storyboard instantiateControllerWithIdentifier:@"AuthorizationViewController"];
            [self presentViewController:authorizationViewController animator:[[ReplaceAnimator alloc] init]];
        } else {
            MainViewController *mainViewController = [self.storyboard instantiateControllerWithIdentifier:@"MainViewController"];
            [self presentViewController:mainViewController animator:[[ReplaceAnimator alloc] init]];
        }
    });
}

@end
