//
//  MBIMBridgeOperation.m
//  kordophoned
//
//  Created by James Magahern on 11/13/18.
//  Copyright © 2018 James Magahern. All rights reserved.
//

#import "MBIMBridgeOperation.h"
#import "MBIMURLUtilities.h"

@interface MBIMBridgeOperation (/*INTERNAL*/)
@property (nonatomic, strong) NSURL *requestURL;
@property (nonatomic, copy)   MBIMBridgeOperationCompletionBlock serverCompletionBlock;
@end

@implementation MBIMBridgeOperation

+ (NSString *)endpointName
{
    // To be inplemented by subclasses
    return @"__unimplemented__";
}

+ (NSMutableDictionary *)_operationClassMapping
{
    static dispatch_once_t onceToken;
    static NSMutableDictionary *operationClassMapping = nil;
    dispatch_once(&onceToken, ^{
        operationClassMapping = [[NSMutableDictionary alloc] init];
    });
    
    return operationClassMapping;
}

+ (dispatch_queue_t)sharedIMAccessQueue
{
    static dispatch_once_t onceToken;
    static dispatch_queue_t accessQueue = nil;
    dispatch_once(&onceToken, ^{
        accessQueue = dispatch_queue_create("IMAccessQueue", DISPATCH_QUEUE_SERIAL);
    });
    
    return accessQueue;
}

+ (void)load
{
    if ([self class] != [MBIMBridgeOperation class]) {
        [[self _operationClassMapping] setObject:[self class] forKey:[self endpointName]];
    }
}

+ (nullable Class)operationClassForEndpointName:(NSString *)endpointName
{
    return [[self _operationClassMapping] objectForKey:endpointName];
}

+ (BOOL)requiresAuthentication
{
    return YES;
}

- (instancetype)initWithRequestURL:(NSURL *)requestURL completion:(MBIMBridgeOperationCompletionBlock)completionBlock
{
    self = [super init];
    if (self) {
        self.requestURL = requestURL;
        self.serverCompletionBlock = completionBlock;
    }
    
    return self;
}

- (NSObject<HTTPResponse> *)cancelAndReturnTimeoutResponse
{
    [self cancel];
    return [[HTTPErrorResponse alloc] initWithErrorCode:500];
}

- (NSString *)valueForQueryItemWithName:(NSString *)queryItemName
{
    return [[self requestURL] valueForQueryItemWithName:queryItemName];
}

@end
