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

#import "AuthorizationProgressViewController.h"

#import "AppDelegate.h"
#import "HPCredentialsHelper.h"

@interface AuthorizationProgressViewController (AuthorizationProgressViewControllerPrivate)

#pragma mark - Private interface

@end

@implementation AuthorizationProgressViewController

#pragma mark - View lifecycle

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

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

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.progressIndicator stopAnimating];
}

#pragma mark - Notification handlers

-(void)onAuthFlowDidFinish:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
#ifdef DEBUG
        NSLog(@"-[AuthorizationViewController onAuthFlowDidFinish:] notification=`%@`", notification);
#endif
        HPCredentials *credentials = [[HPCredentialsHelper sharedHelper] getCredentials];
        
        if (credentials.usable == NO) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Oops!", @"Oops!")
                                                                           message:NSLocalizedString(@"HotPocket couldn't complete this operation.", @"HotPocket couldn't complete this operation.")
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Oh well", @"Oh well")
                                                      style:UIAlertActionStyleDefault
                                                    handler:^(UIAlertAction *action) {
                [alert dismissViewControllerAnimated:YES completion:^{
                    [self.navigationController popViewControllerAnimated:YES];
                }];
            }]];
            
            [self presentViewController:alert animated:YES completion:nil];
        } else {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    });
}

@end
