//
//  QuantumView.m
//  QuantumMetricLibrary
//
//  Created by Aaron Ash on 10/25/21.
//  Copyright © 2021 Quantum Metric. All rights reserved.
//

#import "QuantumView.h"

#import <React/UIView+React.h>

@implementation QuantumView {
    BOOL _privacyReapplyScheduled;
}

-(NSString*)description {
    return [NSString stringWithFormat:@"<QuantumView: %p, privacy: %@, metadata: %@>", self, _privacy, _metadata];
}

-(void)setPrivacy:(NSString *)privacy {
    _privacy = privacy;
    [self qm_applyPrivacy];
}

// QP-26565: RN applies props to a freshly created view and inserts children only
// afterwards, so the mark set in setPrivacy: cascades over an empty subviews array.
-(void)didUpdateReactSubviews {
    [super didUpdateReactSubviews];
    [self qm_schedulePrivacyReapply];
}

// Also covers the Fabric legacy-interop path, where children can land without
// going through this view's RN subview API.
-(void)didAddSubview:(UIView *)subview {
    [super didAddSubview:subview];
    [self qm_schedulePrivacyReapply];
}

// Coalesce to one pass per runloop turn: mounting N children fires N callbacks and
// each apply walks the whole subtree.
-(void)qm_schedulePrivacyReapply {
    if (_privacy.length == 0 || _privacyReapplyScheduled) {
        return;
    }
    _privacyReapplyScheduled = YES;

    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        __typeof(self) strongSelf = weakSelf;
        if (!strongSelf) {
            return;
        }
        strongSelf->_privacyReapplyScheduled = NO;
        [strongSelf qm_applyPrivacy];
    });
}

// Deliberately a no-op for an unset or unrecognized privacy value. Reverting would mean
// calling unmaskView:, which records an explicit "do not mask" that punches a hole in
// mask-everything mode. Doing it properly needs an SDK unencryptView: that does not exist.
-(void)qm_applyPrivacy {
    if (_privacy.length == 0) {
        return;
    }

    Class qmnative = NSClassFromString(@"QMNative");
    if (!qmnative) {
        return;
    }

    NSString *selectorName = nil;
    if ([_privacy isEqualToString:@"mask"]) {
        selectorName = @"maskTextInView:";
    } else if ([_privacy isEqualToString:@"encrypt"]) {
        selectorName = @"encryptView:";
    } else if ([_privacy isEqualToString:@"unmask"]) {
        selectorName = @"unmaskView:";
    } else {
        return;
    }

    SEL selector = NSSelectorFromString(selectorName);
    if ([qmnative respondsToSelector:selector]) {
        [qmnative performSelector:selector withObject:self];
    }
}

@end
