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

#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>

#import "ShareViewController.h"

#import "HPAPI.h"
#import "HPCredentialsHelper.h"
#import "HPShareExtensionHelper.h"
#import "NSBundle+HotPocketExtensions.h"
#import "UnameLabel.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.savingView.hidden = YES;
            
            if (result.error != nil) {
#ifdef DEBUG
                NSLog(@"-[ShareViewController resolveLinkAndSave] saveError=`%@`", result.error);
#endif
                self.errorView.hidden = NO;
            } else {
                self.savedLabel.text = 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.savedLabel.text = 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.doneView.hidden = NO;
            }
        });
    }];
    
    if (callResult == NO) {
        self.savingView.hidden = YES;
        self.errorView.hidden = NO;
    }
}

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

@end

@implementation ShareViewController

#pragma mark - View lifecycle

-(void)viewDidLoad {
    [super viewDidLoad];
    self.savingView.hidden = NO;
    self.needsSetupView.hidden = YES;
    self.doneView.hidden = YES;
    self.errorView.hidden = YES;
    self.unprocessableEntityView.hidden = YES;
    
    self.unameLabel.text = [NSBundle uname];
    
    self.api = [[HPAPI alloc] init];
    if (self.api.rpcClient.hasCredentials == YES) {
        self.savingView.hidden = NO;
        self.needsSetupView.hidden = YES;
    } else {
        self.savingView.hidden = YES;
        self.needsSetupView.hidden = NO;
    }
}

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

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

-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [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.savingView.hidden = YES;
                self.needsSetupView.hidden = NO;
            } else {
                [self resolveLinkAndSave];
            }
        });
    }];
}

#pragma mark - Actions

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

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

@end
