/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * See the NOTICE file distributed with this work for additional
 * information regarding copyright ownership.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


#import "AMSwipeHelpers.h"

#import "FBLogger.h"
#import "FBErrorBuilder.h"


BOOL AMPerformSwipe(NSObject *dest, NSString *direction, NSNumber *velocity, NSError **error)
{
  double velocityValue = .0;
  if (nil != velocity) {
    if ([dest respondsToSelector:NSSelectorFromString(@"swipeUpWithVelocity:")]) {
      velocityValue = [velocity doubleValue];
    } else {
      [FBLogger log:@"Custom velocity values are not supported by the current Xcode SDK. The default velocity will be used instead"];
    }
  }

  if (velocityValue > 0) {
    NSString *selectorName = [NSString stringWithFormat:@"swipe%@WithVelocity:", direction.lowercaseString.capitalizedString];
    SEL selector = NSSelectorFromString(selectorName);
    NSMethodSignature *signature = [dest methodSignatureForSelector:selector];
    if (nil == signature) {
      return [[[FBErrorBuilder builder]
               withDescriptionFormat:@"%@ method of %@ is not supported by the current Xcode SDK", selectorName, [dest className]]
              buildError:error];;
    }
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setSelector:selector];
    [invocation setArgument:&velocityValue atIndex:2];
    [invocation invokeWithTarget:dest];
  } else {
    NSString *selectorName = [NSString stringWithFormat:@"swipe%@", direction.lowercaseString.capitalizedString];
    SEL selector = NSSelectorFromString(selectorName);
    NSMethodSignature *signature = [dest methodSignatureForSelector:selector];
    if (nil == signature) {
      return [[[FBErrorBuilder builder]
               withDescriptionFormat:@"%@ method of %@ is not supported by the current Xcode SDK", selectorName, [dest className]]
              buildError:error];
    }
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
    [invocation setSelector:selector];
    [invocation invokeWithTarget:dest];
  }
  return YES;
}

