//
//  HPSharedItem.m
//  HotPocket
//
//  Created by Tomek Wójcik on 27/09/2025.
//

#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>

#import "HPSharedItem.h"

@implementation HPSharedItem

-(instancetype)initWithPayload:(id)payload typeIdentifier:(NSString *)typeIdentifier error:(NSError *)error {
    if (self = [super init]) {
        self.payload = payload;
        self.typeIdentifier = typeIdentifier;
        self.error = error;
    }
    
    return self;
}

-(NSURL *)maybeURL {
    if (self.error != nil) {
        return nil;
    }
    
    if ([self.typeIdentifier isEqualToString:[UTType typeWithFilenameExtension:@"plist"].identifier] == YES) {
        NSDictionary *propertyList = self.payload;
        NSDictionary *jsHelperResult = [propertyList valueForKey:NSExtensionJavaScriptPreprocessingResultsKey];
        
        if ([jsHelperResult valueForKey:@"iHateComputers"] == nil) {
            return nil;
        }
        
        return [NSURL URLWithString:[jsHelperResult valueForKey:@"url"]];
    } else if ([self.typeIdentifier isEqualToString:@"public.url"] ==  YES) {
        return self.payload;
    } if ([self.typeIdentifier isEqualToString:@"public.plain-text"] ==  YES) {
        return [NSURL URLWithString:self.payload];
    }
    
    return nil;
}

@end
