//
//  NetworkStreamHandler.h
//  CustomKeyboard
//
//  Created by Mac on 2025/11/12.
//

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

typedef NS_ENUM(NSUInteger, NetworkStreamState) {
    NetworkStreamStateIdle,
    NetworkStreamStateConnecting,
    NetworkStreamStateReceiving,
    NetworkStreamStateCompleted,
    NetworkStreamStateError
};

@class NetworkStreamHandler;

@protocol NetworkStreamDelegate <NSObject>

@optional
// 接收到数据块
- (void)networkStream:(NetworkStreamHandler *)stream didReceiveData:(NSData *)data;
// 接收到文本数据（如果是文本内容）
- (void)networkStream:(NetworkStreamHandler *)stream didReceiveText:(NSString *)text;
// 进度更新
- (void)networkStream:(NetworkStreamHandler *)stream downloadProgress:(float)progress;
// 状态改变
- (void)networkStream:(NetworkStreamHandler *)stream stateChanged:(NetworkStreamState)state;
// 请求完成
- (void)networkStream:(NetworkStreamHandler *)stream didCompleteWithError:(NSError * _Nullable)error;

@end

typedef void (^NetworkStreamProgressBlock)(float progress);
typedef void (^NetworkStreamDataBlock)(NSData *data);
typedef void (^NetworkStreamTextBlock)(NSString *text);
typedef void (^NetworkStreamCompletionBlock)(NSError * _Nullable error);

@interface NetworkStreamHandler : NSObject <NSURLSessionDataDelegate>

@property (nonatomic, weak) id<NetworkStreamDelegate> delegate;
@property (nonatomic, assign, readonly) NetworkStreamState state;
@property (nonatomic, strong, readonly) NSURLResponse *response;
@property (nonatomic, assign, readonly) long long totalBytesReceived;

// 初始化方法
- (instancetype)initWithURL:(NSURL *)url;
- (instancetype)initWithRequest:(NSURLRequest *)request;

// 开始请求（使用代理回调）
- (void)startRequest;

// 开始请求（使用 Block 回调）
- (void)startRequestWithProgress:(NetworkStreamProgressBlock _Nullable)progress
                        onData:(NetworkStreamDataBlock _Nullable)dataBlock
                        onText:(NetworkStreamTextBlock _Nullable)textBlock
                     completion:(NetworkStreamCompletionBlock _Nullable)completion;

// 取消请求
- (void)cancelRequest;

// 构建默认请求（包含常见的请求头）
+ (NSURLRequest *)createDefaultRequestWithURL:(NSURL *)url method:(NSString *)method;

@end

NS_ASSUME_NONNULL_END
