//
//  ShareViewController.m
//  macOS (Share Extension)
//
//  Created by Tomek Wójcik on 22/09/2025.
//

#import "ShareViewController.h"

#import "HPAPI.h"
#import "HPShareExtensionHelper.h"
#import "NSBundle+HotPocketExtensions.h"

@implementation ShareViewController (ShareViewControllerPrivate)

#pragma mark - Private interface

-(void)saveURL:(NSURL *)url {
#ifdef DEBUG
    NSLog(@"-[ShareViewController save:] url=`%@`", url);
#endif
    BOOL callResult = [self.api save:url completionHandler:^(NSString * _Nullable callId, HPRPCCallResult * _Nullable result) {
        dispatch_async(dispatch_get_main_queue(), ^{
            self.savingViewHidden = YES;
            
            if (result.error != nil) {
#ifdef DEBUG
                NSLog(@"-[ShareViewController resolveLinkAndSave] saveError=`%@`", result.error);
#endif
                self.errorViewHidden = NO;
            } else {
                self.savedLabelText = NSLocalizedString(
                    @"Your link has been saved!",
                    @"Your link has been saved!"
                );
                
                NSDictionary *save = result.result;
                
                BOOL isNetlocBanned = [(NSNumber *)[save valueForKey:@"is_netloc_banned"] boolValue];
                if (isNetlocBanned == YES) {
                    self.savedLabelText = NSLocalizedString(
                        @"Your link has been saved, but you may want to update its title.",
                        @"Your link has been saved, but you may want to update its title."
                    );
                }
                
                self.doneViewHidden = NO;
            }
        });
    }];
    
    if (callResult == NO) {
        self.savingViewHidden = YES;
        self.errorViewHidden = NO;
    }
}

-(void)resolveLinkAndSave {
    HPShareExtensionHelper *helper = [[HPShareExtensionHelper alloc] initWithContext:self.extensionContext];
    [helper processItems:^(NSURL *url) {
        if (url == nil) {
            self.savingViewHidden = YES;
            self.unprocessableEntityViewHidden = NO;
        } else {
            [self saveURL:url];
        }
    }];
}

@end

@implementation ShareViewController

#pragma mark - View lifecycle

-(NSString *)nibName {
    return @"ShareViewController";
}

-(void)viewDidLoad {
    [super viewDidLoad];
    self.savingViewHidden = NO;
    self.needsSetupViewHidden = YES;
    self.doneViewHidden = YES;
    self.errorViewHidden = YES;
    self.unprocessableEntityViewHidden = YES;
    
    self.uname = [NSBundle uname];
    self.savedLabelText = NSLocalizedString(
        @"Your link has been saved!",
        @"Your link has been saved!"
    );
    
    self.api = [[HPAPI alloc] init];
    if (self.api.rpcClient.hasCredentials == YES) {
        self.savingViewHidden = NO;
        self.needsSetupViewHidden = YES;
    } else {
        self.savingViewHidden = YES;
        self.needsSetupViewHidden = NO;
    }
}

-(void)viewWillAppear {
    [super viewWillAppear];
    [self.progressIndicator startAnimation:self];
}

-(void)viewDidAppear {
    [super viewDidAppear];
    
    [self.api checkAuth:^(BOOL authValid, NSError *error, NSString *callId) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (authValid == NO) {
#ifdef DEBUG
                NSLog(@"-[ShareViewController viewDidAppear:] checkAuthError=`%@`", error);
#endif
                self.savingViewHidden = YES;
                self.needsSetupViewHidden = NO;
            } else {
                [self resolveLinkAndSave];
            }
        });
    }];
}

-(void)viewDidDisappear {
    [super viewDidDisappear];
    [self.progressIndicator stopAnimation:self];
}

#pragma mark - Actions

-(IBAction)close:(id)sender {
    NSExtensionItem *outputItem = [[NSExtensionItem alloc] init];
    
    NSArray *outputItems = @[outputItem];
    [self.extensionContext completeRequestReturningItems:outputItems completionHandler:nil];
}

-(IBAction)cancel:(id)sender {
    NSError *cancelError = [NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil];
    [self.extensionContext cancelRequestWithError:cancelError];
}

@end

