#if !defined(RCT_NEW_ARCH_ENABLED)

#import <ScanbotSDK/ScanbotSDK-Swift.h>
#import "RNScanbotCroppingLegacyView.h"

#if __has_include(<RNScanbotSDK/RNScanbotSDK-Swift.h>)
#import <RNScanbotSDK/RNScanbotSDK-Swift.h>
#else
#import "RNScanbotSDK-Swift.h"
#endif

@interface RNScanbotCroppingLegacyView() <RNScanbotCroppingViewEventsDelegate>
@property (strong, nonatomic) RNScanbotCroppingViewController *scannerViewController;
@property (nonatomic) BOOL attached;
@end

@implementation RNScanbotCroppingLegacyView

- (instancetype)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame]){
        self.attached = false;
        
        self.scannerViewController = [[RNScanbotCroppingViewController alloc] init];
        self.scannerViewController.delegate = self;
    }
 
    return self;
}

- (void)didMoveToWindow {
    [super didMoveToWindow];
    
    if(self.window && !self.attached){
        [self.scannerViewController attachControllerWithParentViewController:[self reactViewController] inView:self];
        self.attached = true;
    }
}

- (void)removeFromSuperview {
    
    self.scannerViewController.delegate = nil;
    [self.scannerViewController detachController];
    self.scannerViewController = nil;
    
    [super removeFromSuperview];
}

// MARK: Sources

- (void) setImageFileSrc:(NSString * _Nullable) source {
    [self.scannerViewController setImageFileSrc:source attached:self.attached];
}

- (void) setImageRefSrc:(NSString * _Nullable) source {
    [self.scannerViewController setImageRefSrc:source attached:self.attached];
}

// MARK: Polygon Configuration

- (void) setEdgeColor:(UIColor * _Nullable) value {
    [self.scannerViewController setEdgeColor:value];
}

- (void) setEdgeLineWidth:(NSNumber * _Nullable) value {
    [self.scannerViewController setEdgeLineWidth:value];
}

- (void) setEdgeColorOnLine:(UIColor * _Nullable) value {
    [self.scannerViewController setEdgeColorOnLine:value];
}

- (void) setAnchorPointsColor:(UIColor * _Nullable) value {
    [self.scannerViewController setAnchorPointsColor:value];
}

// MARK: Commands

- (void)extractCroppedArea {
    [self.scannerViewController extractCroppedArea];
}

- (void)resetPolygon {
    [self.scannerViewController resetPolygon];
}

- (void)rotate:(BOOL)value {
    [self.scannerViewController rotate:value];
}

- (void)detectPolygon {
    [self.scannerViewController detectPolygon];
}

// MARK: Delegate Events

- (void)onExtractCroppingArea:(NSString * _Nonnull)json { 
    if(!self.onCroppedAreaResult){
        return;
    }
    
    self.onCroppedAreaResult(@{@"result": json});
}

- (void)onError:(NSString * _Nonnull)errorMessage errorCode:(NSInteger)errorCode {
    if(!self.onError){
        return;
    }
    
    self.onError(@{@"message": errorMessage, @"code": @(errorCode)});
}

@end

#endif
