//
//  ZYJQNHijackingDetectWrapper.m
//  ZYJHappyDNS
//
//  Created by bailong on 15/7/16.
//  Copyright (c) 2015年 Qiniu Cloud Storage. All rights reserved.
//

#import "ZYJQNHijackingDetectWrapper.h"
#import "ZYJQNDomain.h"
#import "ZYJQNRecord.h"
#import "ZYJQNResolver.h"

@interface ZYJQNHijackingDetectWrapper ()
@property (nonatomic, readonly) ZYJQNResolver *resolver;
@end

@implementation ZYJQNHijackingDetectWrapper

- (NSArray *)query:(ZYJQNDomain *)domain networkInfo:(ZYJQNNetworkInfo *)netInfo error:(NSError *__autoreleasing *)error {
    NSArray *result = [_resolver query:domain networkInfo:netInfo error:error];
    if (((!domain.hasCname) && domain.maxTtl == 0) || result == nil || result.count == 0) {
        return result;
    }
    BOOL hasCname = NO;
    BOOL outOfTtl = NO;
    for (int i = 0; i < result.count; i++) {
        ZYJQNRecord *record = [result objectAtIndex:i];
        if (record.type == kZYJQNTypeCname) {
            hasCname = YES;
        }
        if (domain.maxTtl > 0 && record.type == kZYJQNTypeA && record.ttl > domain.maxTtl) {
            outOfTtl = YES;
        }
    }
    if ((domain.hasCname && !hasCname) || outOfTtl) {
        if (error != nil) {
            *error = [[NSError alloc] initWithDomain:domain.domain code:kZYJQNDomainHijackingCode userInfo:nil];
        }
        return nil;
    }
    return result;
}
- (instancetype)initWithResolver:(ZYJQNResolver *)resolver {
    if (self = [super init]) {
        _resolver = resolver;
    }
    return self;
}

@end
