//
//  SsRefreshHeaderManager.m
//  react-native-ss-rn-native-pull-refresh
//
//  Created by SHEN on 2020/12/4.
//

#import "SsRefreshHeaderManager.h"
#import "SsRefreshHeader.h"
#import <React/RCTUIManager.h>
#import <React/RCTRefreshableProtocol.h>

@interface SsRefreshHeaderManager ()
@property (nonatomic, strong) SsRefreshHeader *refresh;
@end

@implementation SsRefreshHeaderManager
 
RCT_EXPORT_MODULE(SsRefreshHeader)

//将所需参数导出给JS 
RCT_EXPORT_VIEW_PROPERTY(onPull, RCTDirectEventBlock)
RCT_EXPORT_VIEW_PROPERTY(onStateChange, RCTDirectEventBlock)
RCT_EXPORT_VIEW_PROPERTY(bgColor, NSString)
RCT_EXPORT_VIEW_PROPERTY(refreshing, BOOL)

// 导出方法
// js 端需要使用以下方式引入：
// const {endRefreshing} = NativeModules.SsRefreshHeader
//  
RCT_EXPORT_METHOD(beginRefreshing) {
    [self.refresh beginRefreshing];
}

RCT_EXPORT_METHOD(endRefreshing) {
    [self.refresh endRefreshing];
}

RCT_EXPORT_METHOD(clearRefresh) {
    [self.refresh removeFromSuperview];
    self.refresh = NULL;
}

RCT_EXPORT_METHOD(setNativeRefreshing : (nonnull NSNumber *)viewTag toRefreshing : (BOOL)refreshing)
{
  [self.bridge.uiManager addUIBlock:^(RCTUIManager *uiManager, NSDictionary<NSNumber *, UIView *> *viewRegistry) {
    UIView *view = viewRegistry[viewTag];

    if ([view conformsToProtocol:@protocol(RCTRefreshableProtocol)]) {
      [(id<RCTRefreshableProtocol>)view setRefreshing:refreshing];
    } else {
      RCTLogError(@"view must conform to protocol RCTRefreshableProtocol");
    }
  }];
}

- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}

- (UIView *)view
{
    return self.refresh;
}

- (SsRefreshHeader *)refresh {
    if (!_refresh) {
        _refresh = [[SsRefreshHeader alloc] init];
    }
    return _refresh;
} 


@end
