//
// ZYJMQTTCFSocketDecoder.m
// ZYJMQTTClient.framework
//
// Copyright © 2013-2017, Christoph Krey. All rights reserved.
//

#import "ZYJMQTTCFSocketDecoder.h"

#import "ZYJMQTTLog.h"

@interface ZYJMQTTCFSocketDecoder()

@end

@implementation ZYJMQTTCFSocketDecoder

- (instancetype)init {
    self = [super init];
    self.state = ZYJMQTTCFSocketDecoderStateInitializing;
    
    self.stream = nil;
    return self;
}

- (void)open {
    if (self.state == ZYJMQTTCFSocketDecoderStateInitializing) {
        (self.stream).delegate = self;
        [self.stream open];
    }
}

- (void)dealloc {
    [self close];
}

- (void)close {
    [self.stream close];
    [self.stream setDelegate:nil];
}

- (void)stream:(NSStream *)sender handleEvent:(NSStreamEvent)eventCode {
    if (eventCode & NSStreamEventOpenCompleted) {
//        NSLog(@"[ZYJMQTTCFSocketDecoder] NSStreamEventOpenCompleted");
        self.state = ZYJMQTTCFSocketDecoderStateReady;
        [self.delegate decoderDidOpen:self];
    }
    
    if (eventCode & NSStreamEventHasBytesAvailable) {
//        NSLog(@"[ZYJMQTTCFSocketDecoder] NSStreamEventHasBytesAvailable");
        if (self.state == ZYJMQTTCFSocketDecoderStateInitializing) {
            self.state = ZYJMQTTCFSocketDecoderStateReady;
        }
        
        if (self.state == ZYJMQTTCFSocketDecoderStateReady) {
            NSInteger n;
            UInt8 buffer[768];
            
            n = [self.stream read:buffer maxLength:sizeof(buffer)];
            if (n == -1) {
                self.state = ZYJMQTTCFSocketDecoderStateError;
                [self.delegate decoder:self didFailWithError:nil];
            } else {
                NSData *data = [NSData dataWithBytes:buffer length:n];
//                NSLog(@"[ZYJMQTTCFSocketDecoder] received (%lu)=%@...", (unsigned long)data.length,
//                             [data subdataWithRange:NSMakeRange(0, MIN(256, data.length))]);
                [self.delegate decoder:self didReceiveMessage:data];
            }
        }
    }
    if (eventCode & NSStreamEventHasSpaceAvailable) {
//        NSLog(@"[ZYJMQTTCFSocketDecoder] NSStreamEventHasSpaceAvailable");
    }
    
    if (eventCode & NSStreamEventEndEncountered) {
//        NSLog(@"[ZYJMQTTCFSocketDecoder] NSStreamEventEndEncountered");
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            self.state = ZYJMQTTCFSocketDecoderStateInitializing;
            self.error = nil;
            [self.delegate decoderdidClose:self];
        });
    }
    
    if (eventCode & NSStreamEventErrorOccurred) {
//        NSLog(@"[ZYJMQTTCFSocketDecoder] NSStreamEventErrorOccurred");
        self.state = ZYJMQTTCFSocketDecoderStateError;
        self.error = self.stream.streamError;
        [self.delegate decoder:self didFailWithError:self.error];
    }
}

@end
