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

#import "HPSharedItemsContainer.h"

#import "HPSharedItem.h"
#import "NSURL+HotPocketExtensions.h"

@implementation HPSharedItemsContainer (HPSharedItemsContainerPrivate)

-(NSURL *)validatedURL:(NSURL *)url {
    if (url.isUsableInHotPocket == NO) {
        return nil;
    }
    
    return url;
}

@end

@implementation HPSharedItemsContainer

-(instancetype)init {
    if (self = [super init]) {
        self.primaryItem = nil;
        self.candidateItems = [[NSMutableArray alloc] initWithCapacity:1];
    }
    
    return self;
}

-(NSURL *)resolveURL {
    NSURL *result = nil;
    
    if (self.primaryItem != nil) {
        result = [self validatedURL:[self.primaryItem maybeURL]];
    }
    
    if ([self.candidateItems count] > 0) {
        NSUInteger itemCandidateIndex = 0;
        while (result == nil) {
            HPSharedItem *itemCandidate = [self.candidateItems objectAtIndex:itemCandidateIndex];

            result = [self validatedURL:itemCandidate.maybeURL];
            if (result != nil) {
                break;
            }
            
            itemCandidateIndex += 1;
            if (itemCandidateIndex >= [self.candidateItems count]) {
                break;
            }
        }
    }
    
    return result;
}

@end
