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

#import "ZYJMQTTCFSocketEncoder.h"

#import "ZYJMQTTLog.h"

@interface ZYJMQTTCFSocketEncoder()

@property (strong, nonatomic) NSMutableData *buffer;

@end

@implementation ZYJMQTTCFSocketEncoder

- (instancetype)init {
    self = [super init];
    self.state = ZYJMQTTCFSocketEncoderStateInitializing;
    self.buffer = [[NSMutableData alloc] init];
    self.stream = nil;
    return self;
}

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

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

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

- (void)setState:(ZYJMQTTCFSocketEncoderState)state {
    NSLog(@"[ZYJMQTTCFSocketEncoder] setState %ld/%ld", (long)_state, (long)state);
    _state = state;
}

- (void)stream:(NSStream *)sender handleEvent:(NSStreamEvent)eventCode {
    if (eventCode & NSStreamEventOpenCompleted) {
//        NSLog(@"[ZYJMQTTCFSocketEncoder] NSStreamEventOpenCompleted");
    }
    if (eventCode & NSStreamEventHasBytesAvailable) {
//        NSLog(@"[ZYJMQTTCFSocketEncoder] NSStreamEventHasBytesAvailable");
    }
    if (eventCode & NSStreamEventHasSpaceAvailable) {
//        NSLog(@"[ZYJMQTTCFSocketEncoder] NSStreamEventHasSpaceAvailable");
        if (self.state == ZYJMQTTCFSocketEncoderStateInitializing) {
            self.state = ZYJMQTTCFSocketEncoderStateReady;
            [self.delegate encoderDidOpen:self];
        }
        
        if (self.state == ZYJMQTTCFSocketEncoderStateReady) {
            if (self.buffer.length) {
                [self send:nil];
            }
        }
    }
    if (eventCode & NSStreamEventEndEncountered) {
//        NSLog(@"[ZYJMQTTCFSocketEncoder] NSStreamEventEndEncountered");
        self.state = ZYJMQTTCFSocketEncoderStateInitializing;
        self.error = nil;
        [self.delegate encoderdidClose:self];
    }
    if (eventCode & NSStreamEventErrorOccurred) {
//        NSLog(@"[ZYJMQTTCFSocketEncoder] NSStreamEventErrorOccurred");
        self.state = ZYJMQTTCFSocketEncoderStateError;
        self.error = self.stream.streamError;
        [self.delegate encoder:self didFailWithError:self.error];
    }
}

- (BOOL)send:(NSData *)data {
    @synchronized(self) {
        if (self.state != ZYJMQTTCFSocketEncoderStateReady) {
//            NSLog(@"[ZYJMQTTCFSocketEncoder] not ZYJMQTTCFSocketEncoderStateReady");
            return NO;
        }
        
        if (data) {
            [self.buffer appendData:data];
        }
        
        if (self.buffer.length) {
//            NSLog(@"[ZYJMQTTCFSocketEncoder] buffer to write (%lu)=%@...",
//                         (unsigned long)self.buffer.length,
//                         [self.buffer subdataWithRange:NSMakeRange(0, MIN(256, self.buffer.length))]);
            
            NSInteger n = [self.stream write:self.buffer.bytes maxLength:self.buffer.length];
            
            if (n == -1) {
//                NSLog(@"[ZYJMQTTCFSocketEncoder] streamError: %@", self.error);
                self.state = ZYJMQTTCFSocketEncoderStateError;
                self.error = self.stream.streamError;
                return NO;
            } else {
                if (n < self.buffer.length) {
//                    NSLog(@"[ZYJMQTTCFSocketEncoder] buffer partially written: %ld", (long)n);
                }
                [self.buffer replaceBytesInRange:NSMakeRange(0, n) withBytes:NULL length:0];
            }
        }
        return YES;
    }
}

@end
