//
//  UIViewController+UIViewController_KeyCommond.m
//  qm_hardwarekit
//
//  Created by 夏迎霖 on 2017/6/8.
//  Copyright © 2017年 Facebook. All rights reserved.
//

#import "UIViewController+KeyCommond.h"

@implementation UIViewController (UIViewController_KeyCommond)

NSMutableString *resultString;


- (NSMutableString *)resultString {
  if (resultString == nil) {
    resultString = [NSMutableString string];
  }
  return resultString;
}


- (BOOL)canBecomeFirstResponder{
  return YES;
}

- (NSArray *)keyCommands {
  NSMutableArray *array = [NSMutableArray array];
  [array addObject:[UIKeyCommand keyCommandWithInput:@"\r" modifierFlags:0 action:@selector(_handler)]];
  for (int i = 48; i < 58; ++i) {//0..9
    [array addObject:[UIKeyCommand keyCommandWithInput:[NSString stringWithFormat:@"%c", i] modifierFlags:0 action:@selector(commandChanged:)]];
  }
  for (int i = 65; i < 123; ++i) {//A..Za..z
    [array addObject:[UIKeyCommand keyCommandWithInput:[NSString stringWithFormat:@"%c", i] modifierFlags:0 action:@selector(commandChanged:)]];
  }
  return array;
}

- (void)commandChanged:(UIKeyCommand *)command {
  [self.resultString appendString:command.input];
}

- (void)_handler {
  [[NSNotificationCenter defaultCenter] postNotificationName:@"code" object:self.resultString];
  resultString = nil;
}

@end
