/**
 * Copyright (c) 2015-present, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

#import <XCTest/XCTest.h>

#import "FBIntegrationTestCase.h"
#import "FBConfiguration.h"
#import "FBElementUtils.h"
#import "FBElementCache.h"
#import "XCUIElement+FBCaching.h"
#import "FBExceptions.h"
#import "FBResponsePayload.h"
#import "FBTestMacros.h"
#import "XCUIElement.h"
#import "XCUIElement+FBFind.h"
#import "XCUIElement+FBUID.h"
#import "FBXCElementSnapshotWrapper+Helpers.h"
#import "XCUIElement+FBIsVisible.h"
#import "XCUIElement+FBClassChain.h"
#import "XCUIElement+FBResolve.h"
#import "FBXPath.h"
#import "FBXCodeCompatibility.h"
#import "XCUIElement+FBUtilities.h"

@interface XCUIElementFBFindTests : FBIntegrationTestCase
@property (nonatomic, strong) XCUIElement *testedView;
@end

@implementation XCUIElementFBFindTests

- (void)setUp
{
  [super setUp];
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    [self launchApplication];
  });
  self.testedView = self.testedApplication.otherElements[@"MainView"];
  FBAssertWaitTillBecomesTrue(self.testedView.exists);
}

// Based on the lookup snapshot reuse checks from https://github.com/appium/appium-ios/pull/175
- (void)assertLookupSnapshotsWithIndexBinding:(BOOL)boundByIndex
{
  BOOL previousBinding = FBConfiguration.sharedInstance.boundElementsByIndex;
  @try {
    FBConfiguration.sharedInstance.boundElementsByIndex = boundByIndex;
    NSArray<NSArray<XCUIElement *> *> *lookups = @[
      [self.testedView fb_descendantsMatchingClassName:@"XCUIElementTypeButton" shouldReturnAfterFirstMatch:NO],
      [self.testedView fb_descendantsMatchingClassChain:@"**/XCUIElementTypeButton" shouldReturnAfterFirstMatch:NO],
      [self.testedView fb_descendantsMatchingPredicate:[NSPredicate predicateWithFormat:@"type == 'XCUIElementTypeButton'"]
                         shouldReturnAfterFirstMatch:NO],
      [self.testedView fb_descendantsMatchingIdentifier:@"Alerts" shouldReturnAfterFirstMatch:NO],
      [self.testedView fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButton" shouldReturnAfterFirstMatch:NO],
    ];
    for (NSArray<XCUIElement *> *elements in lookups) {
      XCTAssertGreaterThan(elements.count, 1u);
      FBElementCache *cache = [FBElementCache new];
      NSMutableSet<NSString *> *identifiers = [NSMutableSet set];
      for (XCUIElement *element in elements) {
        id<FBXCElementSnapshot> snapshot = element.lastSnapshot;
        if (boundByIndex) {
          // Index-bound matches reuse the snapshots of the query that found them
          XCTAssertNotNil(snapshot);
        } else {
          XCTAssertNil(snapshot);
          XCTAssertNotNil(element.fb_boundAccessibilityElement);
        }
        NSString *uid = element.fb_cacheId;
        XCTAssertEqualObjects([cache storeElement:element], uid);
        // Cache registration and the compact response must not resolve the element again
        XCTAssertEqual(element.lastSnapshot, snapshot);
        XCTAssertEqualObjects(FBDictionaryResponseWithElement(element, YES)[@"element-6066-11e4-a52e-4f735466cecf"], uid);
        XCTAssertEqual(element.lastSnapshot, snapshot);
        [identifiers addObject:uid];
        // Resolve the element independently to catch order/identity errors
        id<FBXCElementSnapshot> resolved = [element fb_standardSnapshot];
        XCTAssertEqualObjects([FBXCElementSnapshotWrapper wdUIDWithSnapshot:resolved], uid);
        if (nil != snapshot) {
          XCTAssertEqualObjects(snapshot.label, resolved.label);
          XCTAssertEqual(snapshot.elementType, resolved.elementType);
        }
        element.lastSnapshot = snapshot;
      }
      XCTAssertEqual(identifiers.count, elements.count);
      FBResponseWithCachedElements(elements, cache, YES);
      for (XCUIElement *element in elements) {
        XCTAssertNil(element.lastSnapshot);
        XCTAssertEqual([cache elementForUUID:element.fb_cacheId], element);
      }
    }
  } @finally {
    FBConfiguration.sharedInstance.boundElementsByIndex = previousBinding;
  }
}

- (void)testLookupSnapshotsWithAccessibilityBinding
{
  [self assertLookupSnapshotsWithIndexBinding:NO];
}

- (void)testLookupSnapshotsWithIndexBinding
{
  [self assertLookupSnapshotsWithIndexBinding:YES];
}

- (void)testDescendantsWithClassName
{
  NSSet<NSString *> *expectedLabels = [NSSet setWithArray:FBMainViewButtonLabels];
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingClassName:@"XCUIElementTypeButton"
                                                                   shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, expectedLabels.count);
  NSArray<NSString *> *labels = [matchingSnapshots valueForKeyPath:@"@distinctUnionOfObjects.label"];
  XCTAssertEqualObjects([NSSet setWithArray:labels], expectedLabels);

  NSArray<NSNumber *> *types = [matchingSnapshots valueForKeyPath:@"@distinctUnionOfObjects.elementType"];
  XCTAssertEqual(types.count, 1, @"matchingSnapshots should contain only one type");
  XCTAssertEqualObjects(types.lastObject, @(XCUIElementTypeButton), @"matchingSnapshots should contain only one type");
}

- (void)testSingleDescendantWithClassName
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingClassName:@"XCUIElementTypeButton"
                                                                   shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
}

- (void)testDescendantsWithIdentifier
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingIdentifier:@"Alerts"
                                                                    shouldReturnAfterFirstMatch:NO];
  int snapshotsCount = 2;
  XCTAssertEqual(matchingSnapshots.count, snapshotsCount);
  XCTAssertEqual(matchingSnapshots.firstObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
  NSArray<XCUIElement *> *selfElementsById = [matchingSnapshots.lastObject fb_descendantsMatchingIdentifier:@"Alerts" shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(selfElementsById.count, 1);
}

- (void)testSingleDescendantWithIdentifier
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingIdentifier:@"Alerts"
                                                                    shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
}

- (void)testStableInstance
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingIdentifier:@"Alerts"
                                                                    shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 1);
  for (XCUIElement *el in @[
    matchingSnapshots.lastObject,
    [matchingSnapshots.lastObject fb_stableInstanceWithUid:[matchingSnapshots.lastObject fb_uid]]
  ]) {
    XCTAssertEqual(el.elementType, XCUIElementTypeButton);
    XCTAssertEqualObjects(el.label, @"Alerts");
  }
}

- (void)testSingleDescendantWithMissingIdentifier
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingIdentifier:@"blabla" shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 0);
}

- (void)testDescendantsWithXPathQuery
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButton[@label='Alerts']"
                                                                    shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
}

- (void)testSelfWithXPathQuery
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedApplication fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeApplication"
                                                                           shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeApplication);
}

- (void)testSingleDescendantWithXPathQuery
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedApplication fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButton[@hittable='true']"
                                                                           shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCUIElement *matchingSnapshot = [matchingSnapshots firstObject];
  XCTAssertNotNil(matchingSnapshot);
  XCTAssertEqual(matchingSnapshot.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshot.label, @"Alerts");
}

- (void)testSingleDescendantWithXPathQueryNoMatches
{
  XCUIElement *matchingSnapshot = [[self.testedView fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButtonnn"
                                                         shouldReturnAfterFirstMatch:YES] firstObject];
  XCTAssertNil(matchingSnapshot);
}

- (void)testSingleLastDescendantWithXPathQuery
{
  XCUIElement *matchingSnapshot = [[self.testedView fb_descendantsMatchingXPathQuery:@"(//XCUIElementTypeButton)[last()]"
                                                         shouldReturnAfterFirstMatch:YES] firstObject];
  XCTAssertNotNil(matchingSnapshot);
  XCTAssertEqual(matchingSnapshot.elementType, XCUIElementTypeButton);
}

- (void)testDescendantsWithXPathQueryNoMatches
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButton[@label='Alerts1']"
                                                                    shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 0);
}

- (void)testDescendantsWithComplexXPathQuery
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingXPathQuery:@"//*[@label='Scrolling']/preceding::*[boolean(string(@label))]"
                                                                    shouldReturnAfterFirstMatch:NO];
  int snapshotsCount = 6;
  XCTAssertEqual(matchingSnapshots.count, snapshotsCount);
}

- (void)testDescendantsWithWrongXPathQuery
{
  XCTAssertThrowsSpecificNamed([self.testedView fb_descendantsMatchingXPathQuery:@"//*[blabla(@label, Scrolling')]"
                                                     shouldReturnAfterFirstMatch:NO],
                               NSException, FBInvalidXPathException);
}

- (void)testFirstDescendantWithWrongXPathQuery
{
  XCTAssertThrowsSpecificNamed([self.testedView fb_descendantsMatchingXPathQuery:@"//*[blabla(@label, Scrolling')]"
                                                     shouldReturnAfterFirstMatch:YES],
                               NSException, FBInvalidXPathException);
}

- (void)testVisibleDescendantWithXPathQuery
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButton[@name='Alerts' and @enabled='true' and @visible='true']" shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
  XCTAssertTrue(matchingSnapshots.lastObject.isEnabled);
  XCTAssertTrue(matchingSnapshots.lastObject.fb_isVisible);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
}

- (void)testDescendantsWithPredicateString
{
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"label = 'Alerts'"];
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingPredicate:predicate
                                                                   shouldReturnAfterFirstMatch:NO];
  int snapshotsCount = 2;
  XCTAssertEqual(matchingSnapshots.count, snapshotsCount);
  XCTAssertEqual(matchingSnapshots.firstObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
  NSPredicate *selfPredicate = [NSPredicate predicateWithFormat:@"label == 'Alerts'"];
  NSArray<XCUIElement *> *selfElementsByPredicate = [matchingSnapshots.lastObject fb_descendantsMatchingPredicate:selfPredicate
                                                                                      shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(selfElementsByPredicate.count, 1);
}

- (void)testSelfWithPredicateString
{
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type == 'XCUIElementTypeApplication'"];
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedApplication fb_descendantsMatchingPredicate:predicate
                                                                          shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeApplication);
}

- (void)testSingleDescendantWithPredicateString
{
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type = 'XCUIElementTypeButton'"];
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingPredicate:predicate shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
}

- (void)testSingleDescendantWithPredicateStringByIndex
{
  NSPredicate *predicate = [NSPredicate predicateWithFormat:@"type == 'XCUIElementTypeButton' AND index == 2"];
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingPredicate:predicate shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
}

- (void)testDescendantsWithPropertyStrict
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingProperty:@"label"
                                                                                        value:@"Alert"
                                                                                partialSearch:NO];
  XCTAssertEqual(matchingSnapshots.count, 0);
  matchingSnapshots = [self.testedView fb_descendantsMatchingProperty:@"label" value:@"Alerts" partialSearch:NO];
  int snapshotsCount = 2;
  XCTAssertEqual(matchingSnapshots.count, snapshotsCount);
  XCTAssertEqual(matchingSnapshots.firstObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
}

- (void)testGlobalWithPropertyStrict
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedApplication fb_descendantsMatchingProperty:@"label"
                                                                                               value:@"Alert"
                                                                                       partialSearch:NO];
  XCTAssertEqual(matchingSnapshots.count, 0);
  matchingSnapshots = [self.testedApplication fb_descendantsMatchingProperty:@"label" value:@"Alerts" partialSearch:NO];
  int snapshotsCount = 2;
  XCTAssertEqual(matchingSnapshots.count, snapshotsCount);
  XCTAssertEqual(matchingSnapshots.firstObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
}

- (void)testDescendantsWithPropertyPartial
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingProperty:@"label"
                                                                                        value:@"Alerts"
                                                                                partialSearch:NO];
  int snapshotsCount = 2;
  XCTAssertEqual(matchingSnapshots.count, snapshotsCount);
  XCTAssertEqual(matchingSnapshots.firstObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, @"Alerts");
}

- (void)testDescendantsWithClassChain
{
  NSArray<XCUIElement *> *matchingSnapshots;
  NSString *queryString =@"XCUIElementTypeWindow/XCUIElementTypeOther/**/XCUIElementTypeButton";
  matchingSnapshots = [self.testedApplication fb_descendantsMatchingClassChain:queryString
                                                   shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, FBMainViewButtonLabels.count); // /XCUIElementTypeButton
  for (XCUIElement *matchingSnapshot in matchingSnapshots) {
    XCTAssertEqual(matchingSnapshot.elementType, XCUIElementTypeButton);
  }
}

- (void)testDescendantsWithClassChainWithIndex
{
  NSArray<XCUIElement *> *matchingSnapshots;
  // iPhone
  NSString *queryString = @"XCUIElementTypeWindow/*/*/*/*[2]/*/*/XCUIElementTypeButton";
  matchingSnapshots = [self.testedApplication fb_descendantsMatchingClassChain:queryString
                                                   shouldReturnAfterFirstMatch:NO];
  if (matchingSnapshots.count == 0) {
    // iPad
    queryString = @"XCUIElementTypeWindow/*/*/*/*/*[2]/*/*/XCUIElementTypeButton";
    matchingSnapshots = [self.testedApplication fb_descendantsMatchingClassChain:queryString
                                                     shouldReturnAfterFirstMatch:NO];
  }
  XCTAssertEqual(matchingSnapshots.count, FBMainViewButtonLabels.count); // /XCUIElementTypeButton
  for (XCUIElement *matchingSnapshot in matchingSnapshots) {
    XCTAssertEqual(matchingSnapshot.elementType, XCUIElementTypeButton);
  }
}

- (void)testDescendantsWithClassChainAndPredicates
{
  NSArray<XCUIElement *> *matchingSnapshots;
  NSString *queryString = @"XCUIElementTypeWindow/**/XCUIElementTypeButton[`label BEGINSWITH 'A'`]";
  matchingSnapshots = [self.testedApplication fb_descendantsMatchingClassChain:queryString
                                                   shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 2);
  XCTAssertEqualObjects([matchingSnapshots firstObject].label, @"Alerts");
  XCTAssertEqualObjects([matchingSnapshots lastObject].label, @"Attributes");
}

- (void)testDescendantsWithIndirectClassChainAndPredicates
{
  NSString *queryString = @"XCUIElementTypeWindow/**/XCUIElementTypeButton[`label BEGINSWITH 'A'`]";
  NSArray<XCUIElement *> *simpleQueryMatches = [self.testedApplication fb_descendantsMatchingClassChain:queryString
                                                                            shouldReturnAfterFirstMatch:NO];
  NSArray<XCUIElement *> *deepQueryMatches = [self.testedApplication fb_descendantsMatchingClassChain:@"XCUIElementTypeWindow/**/XCUIElementTypeButton[`label BEGINSWITH 'A'`]"
                                                                          shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(simpleQueryMatches.count, deepQueryMatches.count);
  XCTAssertEqualObjects([simpleQueryMatches firstObject].label, [deepQueryMatches firstObject].label);
  XCTAssertEqualObjects([simpleQueryMatches lastObject].label, [deepQueryMatches lastObject].label);
}

- (void)testClassChainWithDescendantPredicate
{
  NSArray<XCUIElement *> *simpleQueryMatches = [self.testedApplication fb_descendantsMatchingClassChain:@"XCUIElementTypeWindow/*/*[1]"
                                                                            shouldReturnAfterFirstMatch:NO];
  NSArray<XCUIElement *> *predicateQueryMatches = [self.testedApplication fb_descendantsMatchingClassChain:@"XCUIElementTypeWindow/*/*[$type == 'XCUIElementTypeButton' AND label BEGINSWITH 'A'$]"
                                                                               shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(simpleQueryMatches.count, predicateQueryMatches.count);
  XCTAssertEqual([simpleQueryMatches firstObject].elementType, [predicateQueryMatches firstObject].elementType);
  XCTAssertEqual([simpleQueryMatches lastObject].elementType, [predicateQueryMatches lastObject].elementType);
}

- (void)testSingleDescendantWithComplexIndirectClassChain
{
  NSArray<XCUIElement *> *queryMatches = [self.testedApplication fb_descendantsMatchingClassChain:@"**/*/XCUIElementTypeButton[2]"
                                                                      shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(queryMatches.count, 1);
  XCTAssertEqual(queryMatches.lastObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(queryMatches.lastObject.label, @"Deadlock app");
}

- (void)testSingleDescendantWithComplexIndirectClassChainAndZeroMatches
{
  NSArray<XCUIElement *> *queryMatches = [self.testedApplication fb_descendantsMatchingClassChain:@"**/*/XCUIElementTypeWindow"
                                                                      shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(queryMatches.count, 0);
}

- (void)testDescendantsWithClassChainAndPredicatesAndIndexes
{
  NSArray<XCUIElement *> *matchingSnapshots;
  NSString *queryString = @"XCUIElementTypeWindow[`name != 'bla'`]/**/XCUIElementTypeButton[`label BEGINSWITH \"A\"`][1]";
  matchingSnapshots = [self.testedApplication fb_descendantsMatchingClassChain:queryString
                                                   shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqualObjects([matchingSnapshots firstObject].label, @"Alerts");
}

- (void)testSingleDescendantWithClassChain
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView fb_descendantsMatchingClassChain:@"XCUIElementTypeButton"
                                                                    shouldReturnAfterFirstMatch:YES];
  
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
  XCTAssertTrue([matchingSnapshots.lastObject.label isEqualToString:@"Alerts"]);
}

- (void)testSingleDescendantWithClassChainAndNegativeIndex
{
  NSArray<XCUIElement *> *matchingSnapshots;
  matchingSnapshots = [self.testedView fb_descendantsMatchingClassChain:@"XCUIElementTypeButton[-1]"
                                            shouldReturnAfterFirstMatch:YES];
  
  XCTAssertEqual(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeButton);
  XCTAssertEqualObjects(matchingSnapshots.lastObject.label, FBMainViewButtonLabels.lastObject);
  
  matchingSnapshots = [self.testedView fb_descendantsMatchingClassChain:@"XCUIElementTypeButton[-10]"
                                            shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 0);
}

- (void)testInvalidQueryWithClassChain
{
  XCTAssertThrowsSpecificNamed([self.testedView fb_descendantsMatchingClassChain:@"NoXCUIElementTypePrefix"
                                                     shouldReturnAfterFirstMatch:YES],
                               NSException, FBClassChainQueryParseException);
}

- (void)testHandleInvalidQueryWithClassChainAsNoElementWithoutError
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedView
                                               fb_descendantsMatchingClassChain:@"XCUIElementTypeBlabla"
                                               shouldReturnAfterFirstMatch:YES];
  XCTAssertEqual(matchingSnapshots.count, 0);
}

- (void)testClassChainWithInvalidPredicate
{
  XCTAssertThrowsSpecificNamed([self.testedApplication fb_descendantsMatchingClassChain:@"XCUIElementTypeWindow[`bla != 'bla'`]"
                                                            shouldReturnAfterFirstMatch:NO],
                               NSException, FBUnknownAttributeException);;
}


- (void)testUidsOfAccessibilityBoundElementsDoNotNeedSnapshots
{
  BOOL previousBinding = FBConfiguration.sharedInstance.boundElementsByIndex;
  FBConfiguration.sharedInstance.boundElementsByIndex = NO;
  @try {
    NSArray<XCUIElement *> *matches = [self.testedView fb_descendantsMatchingClassName:@"XCUIElementTypeButton"
                                                            shouldReturnAfterFirstMatch:NO];
    XCTAssertEqual(matches.count, FBMainViewButtonLabels.count);
    for (XCUIElement *match in matches) {
      XCTAssertNotNil(match.fb_boundAccessibilityElement);
      match.lastSnapshot = nil;
      NSString *uid = match.fb_uid;
      XCTAssertNil(match.lastSnapshot, @"Getting the uid must not resolve the element");
      XCTAssertEqualObjects(uid, [FBXCElementSnapshotWrapper wdUIDWithSnapshot:[match fb_standardSnapshot]]);
    }
  } @finally {
    FBConfiguration.sharedInstance.boundElementsByIndex = previousBinding;
  }
}

- (void)testElementResponsesMatchSnapshotUids
{
  BOOL previousBinding = FBConfiguration.sharedInstance.boundElementsByIndex;
  FBConfiguration.sharedInstance.boundElementsByIndex = NO;
  @try {
    NSArray<XCUIElement *> *matches = [self.testedView fb_descendantsMatchingClassName:@"XCUIElementTypeButton"
                                                            shouldReturnAfterFirstMatch:NO];
    XCTAssertEqual(matches.count, FBMainViewButtonLabels.count);
    NSMutableArray<NSString *> *expectedUids = [NSMutableArray array];
    NSMutableArray<NSString *> *expectedLabels = [NSMutableArray array];
    for (XCUIElement *match in matches) {
      id<FBXCElementSnapshot> snapshot = [match fb_standardSnapshot];
      [expectedUids addObject:(NSString *)[FBXCElementSnapshotWrapper wdUIDWithSnapshot:snapshot]];
      [expectedLabels addObject:snapshot.label];
      match.lastSnapshot = nil;
    }
    XCTAssertEqual([NSSet setWithArray:expectedUids].count, expectedUids.count);

    FBElementCache *cache = [FBElementCache new];
    NSArray *payloads = @[@(YES), @(NO)];
    for (NSNumber *compact in payloads) {
      id<FBResponsePayload> payload = FBResponseWithCachedElements(matches, cache, compact.boolValue);
      XCTAssertNotNil(payload);
      for (NSUInteger i = 0; i < matches.count; i++) {
        NSDictionary *response = FBDictionaryResponseWithElement(matches[i], compact.boolValue);
        XCTAssertEqualObjects(response[@"ELEMENT"], expectedUids[i]);
        if (!compact.boolValue) {
          XCTAssertEqualObjects(response[@"label"], expectedLabels[i]);
        }
        XCTAssertTrue([cache hasElementWithUUID:expectedUids[i]]);
      }
    }
  } @finally {
    FBConfiguration.sharedInstance.boundElementsByIndex = previousBinding;
  }
}

- (void)testXPathMatchesAreBoundWithoutResolvingEachElement
{
  NSArray<XCUIElement *> *matches = [self.testedView fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButton"
                                                          shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matches.count, FBMainViewButtonLabels.count);
  NSMutableSet<NSString *> *uids = [NSMutableSet set];
  for (XCUIElement *match in matches) {
    XCTAssertNotNil(match.fb_boundAccessibilityElement);
    XCTAssertNil(match.lastSnapshot, @"Matches must not retain the snapshots they were found with");
    NSString *uid = match.fb_uid;
    XCTAssertNil(match.lastSnapshot, @"Getting the uid must not resolve the element");
    XCTAssertEqualObjects(uid, [FBXCElementSnapshotWrapper wdUIDWithSnapshot:[match fb_standardSnapshot]]);
    XCTAssertEqual(match.elementType, XCUIElementTypeButton);
    [uids addObject:uid];
  }
  XCTAssertEqual(uids.count, matches.count);
  XCTAssertEqualObjects([matches valueForKey:@"label"], FBMainViewButtonLabels);
}

- (void)testXPathMatchesAreIndexBoundWhenRequested
{
  BOOL previousBinding = FBConfiguration.sharedInstance.boundElementsByIndex;
  FBConfiguration.sharedInstance.boundElementsByIndex = YES;
  @try {
    NSArray<XCUIElement *> *matches = [self.testedView fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeButton"
                                                            shouldReturnAfterFirstMatch:NO];
    XCTAssertEqual(matches.count, FBMainViewButtonLabels.count);
    for (XCUIElement *match in matches) {
      XCTAssertNil(match.fb_boundAccessibilityElement);
    }
    XCTAssertEqualObjects([matches valueForKey:@"label"], FBMainViewButtonLabels);
  } @finally {
    FBConfiguration.sharedInstance.boundElementsByIndex = previousBinding;
  }
}

@end

@interface XCUIElementFBFindTests_AttributesPage : FBIntegrationTestCase
@end
@implementation XCUIElementFBFindTests_AttributesPage

- (void)setUp
{
  [super setUp];
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    [self launchApplication];
    [self goToAttributesPage];
  });
}

- (void)testNestedQueryWithClassChain
{
  NSString *queryString = @"XCUIElementTypePicker";
  FBAssertWaitTillBecomesTrue(self.testedApplication.buttons[@"Button"].fb_isVisible);
  XCUIElement *datePicker = [self.testedApplication
                             descendantsMatchingType:XCUIElementTypeDatePicker].allElementsBoundByIndex.firstObject;
  NSArray<XCUIElement *> *matches = [datePicker fb_descendantsMatchingClassChain:queryString
                                                     shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matches.count, 1);

  XCUIElementType expectedType = XCUIElementTypePicker;
  XCTAssertEqual([matches firstObject].elementType, expectedType);
}

@end

@interface XCUIElementFBFindTests_ScrollPage : FBIntegrationTestCase
@end
@implementation XCUIElementFBFindTests_ScrollPage

- (void)setUp
{
  [super setUp];
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    [self launchApplication];
    [self goToScrollPageWithCells:YES];
  });
}

- (void)testInvisibleDescendantWithXPathQuery
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedApplication fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeStaticText[@visible='false']"
                                                                           shouldReturnAfterFirstMatch:NO];
  XCTAssertGreaterThan(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeStaticText);
  XCTAssertFalse(matchingSnapshots.lastObject.fb_isVisible);
}

- (void)testNonHittableDescendantWithXPathQuery
{
  NSArray<XCUIElement *> *matchingSnapshots = [self.testedApplication fb_descendantsMatchingXPathQuery:@"//XCUIElementTypeStaticText[@hittable='false']"
                                                                           shouldReturnAfterFirstMatch:NO];
  XCTAssertGreaterThan(matchingSnapshots.count, 1);
  XCTAssertEqual(matchingSnapshots.lastObject.elementType, XCUIElementTypeStaticText);
  XCTAssertFalse(matchingSnapshots.lastObject.fb_isVisible);
}

@end

@interface XCUIElementFBFindTests_DeepHierarchyPage : FBIntegrationTestCase
@end
@implementation XCUIElementFBFindTests_DeepHierarchyPage

- (void)setUp
{
  [super setUp];
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
    [self launchApplication];
    [self goToDeepHierarchyPage];
  });
}

// No intermediate segment has a position here (only the final one does), so
// this exercises the query-based class chain strategy - the fast path for
// the common case. See fb_hasIntermediatePosition: in XCUIElement+FBClassChain.m.
- (void)testClassChainWithoutIntermediatePositionOnDeepHierarchy
{
  NSString *query = @"**/XCUIElementTypeOther[`label BEGINSWITH \"View 19\"`]/XCUIElementTypeOther[1]";
  NSArray<XCUIElement *> *matches = [self.testedApplication fb_descendantsMatchingClassChain:query
                                                                   shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matches.count, 1);
  XCTAssertEqualObjects(matches.firstObject.label, @"View 20");
}

// The first segment here has an explicit position and is not the last
// segment in the chain, so this exercises the snapshot-walk class chain
// strategy - the one that avoids paying an extra accessibility round trip
// per intermediate indexed segment.
- (void)testClassChainWithIntermediatePositionOnDeepHierarchy
{
  NSString *query = @"**/XCUIElementTypeOther[`label == \"View 10\"`][1]/**/XCUIElementTypeOther[`label BEGINSWITH \"View 19\"`]";
  NSArray<XCUIElement *> *matches = [self.testedApplication fb_descendantsMatchingClassChain:query
                                                                   shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matches.count, 1);
  XCTAssertEqualObjects(matches.firstObject.label, @"View 19");
}

// Exercises the snapshot-walk strategy with several intermediate positions
// (the shape it exists for), as opposed to testPerformanceOfClassChainLookupOnDeepHierarchy
// above, which only has a position on the final segment and stays on the
// query-based strategy. Kept within the default snapshotMaxDepth (50)
// combined with the app's own chrome depth above this fixture's root -
// going deeper hit a native kAXErrorIllegalArgument even after raising
// snapshotMaxDepth, which looks like a platform-level limitation
// independent of this lookup, not something to route around here.
- (void)testPerformanceOfMultiCheckpointClassChainLookupOnDeepHierarchy
{
  NSString *query = @"**/XCUIElementTypeOther[`label == \"View 5\"`][1]/**/XCUIElementTypeOther[`label == \"View 15\"`][1]/**/XCUIElementTypeOther[`label == \"View 25\"`][1]/**/XCUIElementTypeOther[`label BEGINSWITH \"View 30\"`]";
  [self measureBlock:^{
    NSArray<XCUIElement *> *matches = [self.testedApplication fb_descendantsMatchingClassChain:query
                                                                     shouldReturnAfterFirstMatch:NO];
    XCTAssertEqual(matches.count, 1);
  }];
}

// Not a strict pass/fail assertion (timings vary across machines/CI) - this
// records a measurement baseline so future regressions on this lookup show
// up in Xcode's test reports.
- (void)testPerformanceOfClassChainLookupOnDeepHierarchy
{
  NSString *query = @"**/XCUIElementTypeOther[`label BEGINSWITH \"View 19\"`]/XCUIElementTypeOther[1]";
  [self measureBlock:^{
    NSArray<XCUIElement *> *matches = [self.testedApplication fb_descendantsMatchingClassChain:query
                                                                     shouldReturnAfterFirstMatch:NO];
    XCTAssertEqual(matches.count, 1);
  }];
}

@end

@interface XCUIElementFBFindTests_StaleAppSnapshot : FBIntegrationTestCase
@end
@implementation XCUIElementFBFindTests_StaleAppSnapshot

- (void)testCachedLookupStillChecksStalenessAfterNavigation
{
  [self launchApplication];
  XCUIElement *element = [self.testedApplication fb_descendantsMatchingClassChain:
    @"**/XCUIElementTypeButton[`label == 'Alerts'`]" shouldReturnAfterFirstMatch:NO].firstObject;
  NSString *uid = element.fb_cacheId;
  FBElementCache *cache = [FBElementCache new];
  FBResponseWithCachedElement(element, cache, YES);
  XCTAssertNil(element.lastSnapshot);

  [self goToAttributesPage];
  XCTAssertThrowsSpecificNamed([cache elementForUUID:uid checkStaleness:YES], NSException, FBStaleElementException);
  XCTAssertFalse([cache hasElementWithUUID:uid]);
}

// Regression test for https://github.com/appium/appium/issues/22672.
- (void)testClassChainWithIntermediatePositionAfterStaleAppSnapshot
{
  [self launchApplication];
  // Simulates a stale snapshot cached by an earlier, unrelated command (e.g. GET /source).
  [self.testedApplication fb_customSnapshot];
  [self goToDeepHierarchyPage];

  NSString *query = @"**/XCUIElementTypeOther[`label == \"View 10\"`][1]/**/XCUIElementTypeOther[`label BEGINSWITH \"View 19\"`]";
  NSArray<XCUIElement *> *matches = [self.testedApplication fb_descendantsMatchingClassChain:query
                                                                   shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matches.count, 1);
  XCTAssertEqualObjects(matches.firstObject.label, @"View 19");
}

@end


@interface XCUIElementFBFindTests_IdentifierSemantics : FBIntegrationTestCase
@end

@implementation XCUIElementFBFindTests_IdentifierSemantics

- (void)setUp
{
  [super setUp];
  self.testedApplication.launchArguments = @[@"--identifier-lookup-test"];
  [self.testedApplication launch];
  XCTAssertTrue([self.testedApplication.otherElements[@"IdentifierLookupFixture"] waitForExistenceWithTimeout:5]);
}

- (void)tearDown
{
  [self.testedApplication terminate];
  [super tearDown];
}

- (void)testIdentifierTakesPrecedenceOverLabel
{
  NSArray<XCUIElement *> *matches = [self.testedApplication fb_descendantsMatchingIdentifier:@"something"
                                                              shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(matches.count, 4);
  XCTAssertEqualObjects([matches valueForKey:@"label"], (@[@"other label", @"something", @"something", @"something"]));
  XCTAssertEqual([self.testedApplication fb_descendantsMatchingIdentifier:@"different" shouldReturnAfterFirstMatch:NO].count, 1);
  // A matching label must not override a different, nonempty identifier.
  XCTAssertEqual([self.testedApplication fb_descendantsMatchingIdentifier:@"other label" shouldReturnAfterFirstMatch:NO].count, 0);
}

- (void)testEmptyIdentifierDoesNotMatchEmptyAccessibilityId
{
  // The fixture has an empty identifier with a nonempty label at index 2,
  // and an empty identifier with an empty label at index 5.
  XCUIElement *labelFallback = [self.testedApplication.staticTexts elementBoundByIndex:2];
  XCUIElement *unnamed = [self.testedApplication.staticTexts elementBoundByIndex:5];
  XCTAssertEqualObjects(labelFallback.identifier, @"");
  XCTAssertEqualObjects(labelFallback.label, @"something");
  XCTAssertEqualObjects(unnamed.identifier, @"");
  XCTAssertEqualObjects(unnamed.label, @"");

  // Regression guard for "identifier != nil AND identifier != ''": the old
  // wdName lookup used the nonempty label, or nil when both fields were empty.
  // Thus an empty query matched neither element. Checking only identifier != nil
  // would instead let identifier == @"" match both, changing existing behavior.
  BOOL previousFirstMatch = FBConfiguration.sharedInstance.useFirstMatch;
  @try {
    for (NSNumber *useFirstMatch in @[@NO, @YES]) {
      FBConfiguration.sharedInstance.useFirstMatch = useFirstMatch.boolValue;
      for (NSNumber *firstMatch in @[@NO, @YES]) {
        XCTAssertEqual([self.testedApplication fb_descendantsMatchingIdentifier:@""
                                                  shouldReturnAfterFirstMatch:firstMatch.boolValue].count, 0,
                       @"An empty accessibility ID must not match empty identifiers, even when they are non-nil");
      }
    }
  } @finally {
    FBConfiguration.sharedInstance.useFirstMatch = previousFirstMatch;
  }
}

- (void)testMissingQuotedAndUnicodeIdentifiers
{
  for (NSNumber *firstMatch in @[@NO, @YES]) {
    XCTAssertEqual([self.testedApplication fb_descendantsMatchingIdentifier:@"missing-target" shouldReturnAfterFirstMatch:firstMatch.boolValue].count, 0);
    XCTAssertEqual([self.testedApplication fb_descendantsMatchingIdentifier:@"quote'\"é" shouldReturnAfterFirstMatch:firstMatch.boolValue].count, 1);
    XCTAssertEqual([self.testedApplication fb_descendantsMatchingIdentifier:@"日本語" shouldReturnAfterFirstMatch:firstMatch.boolValue].count, 1);
  }
}

- (void)testFirstMatchAndParentScopeWithBothBindings
{
  BOOL previousBinding = FBConfiguration.sharedInstance.boundElementsByIndex;
  @try {
    for (NSNumber *indexed in @[@NO, @YES]) {
      FBConfiguration.sharedInstance.boundElementsByIndex = indexed.boolValue;
      // Use the element returned by WDA lookup, as the element-scoped endpoint does.
      XCUIElement *parent = [self.testedApplication fb_descendantsMatchingIdentifier:@"IdentifierLookupFixture"
                                                          shouldReturnAfterFirstMatch:YES].firstObject;
      XCTAssertNotNil(parent);
      // The HTTP endpoint resolves the parent when registering its element ID.
      XCTAssertNotNil(parent.fb_uid);
      NSArray<XCUIElement *> *matches = [parent fb_descendantsMatchingIdentifier:@"something" shouldReturnAfterFirstMatch:NO];
      NSArray<XCUIElement *> *first = [parent fb_descendantsMatchingIdentifier:@"something" shouldReturnAfterFirstMatch:YES];
      XCTAssertEqual(matches.count, 4);
      XCTAssertEqual(first.count, 1);
      XCTAssertEqualObjects(first.firstObject.fb_uid, matches.firstObject.fb_uid);
      NSArray<XCUIElement *> *selfMatches = [parent fb_descendantsMatchingIdentifier:@"IdentifierLookupFixture" shouldReturnAfterFirstMatch:NO];
      XCTAssertEqual(selfMatches.count, 1);
      XCTAssertEqualObjects(selfMatches.firstObject.fb_uid, parent.fb_uid);
    }
  } @finally {
    FBConfiguration.sharedInstance.boundElementsByIndex = previousBinding;
  }
}

- (void)testIdentifierChangesAreObserved
{
  NSArray<XCUIElement *> *before = [self.testedApplication fb_descendantsMatchingIdentifier:@"something" shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(before.count, 4);
  NSArray<NSString *> *beforeIds = [before valueForKey:@"fb_uid"];
  [self.testedApplication.buttons[@"mutateIdentifier"] tap];
  NSArray<XCUIElement *> *after = [self.testedApplication fb_descendantsMatchingIdentifier:@"something" shouldReturnAfterFirstMatch:NO];
  NSArray<XCUIElement *> *changed = [self.testedApplication fb_descendantsMatchingIdentifier:@"changed" shouldReturnAfterFirstMatch:NO];
  XCTAssertEqual(after.count, 3);
  XCTAssertEqual(changed.count, 1);
  XCTAssertEqualObjects([after valueForKey:@"fb_uid"], [beforeIds subarrayWithRange:NSMakeRange(1, 3)]);
  XCTAssertEqualObjects(changed.firstObject.fb_uid, beforeIds.firstObject);
}

@end
