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

#import "ShareViewController.h"

#import "HPAPI.h"
#import "HPShareExtensionHelper.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.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;
    
    NSBundle *mainBundle = [NSBundle mainBundle];
    self.uname = [NSString  stringWithFormat:@"HotPocket v%@ (%@)", [mainBundle.infoDictionary valueForKey:@"CFBundleShortVersionString"], [mainBundle.infoDictionary valueForKey:@"CFBundleVersion"]];
    
    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

