//
//  UITextField+Addition.m
//  EugineAPISample
//
//  Created by aaab on 2023/02/04.
//

#import "UITextField+Addition.h"

@implementation UITextField (Addition)


- (void)addNumericAccessory:(BOOL)addPlusMinus {
    UIToolbar *numberToolbar = [[UIToolbar alloc] init];
    numberToolbar.barStyle = UIBarStyleDefault;

    NSMutableArray *accessories = [NSMutableArray array];

    if (addPlusMinus) {
        UIBarButtonItem *plusBarButton = [[UIBarButtonItem alloc] initWithTitle:@".(DOT)" style:UIBarButtonItemStylePlain target:self action:@selector(dotPressed)];
        [plusBarButton setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                               [UIFont fontWithName:@"Helvetica-Bold" size:25.0], NSFontAttributeName,
//                                               [UIColor blackColor], NSForegroundColorAttributeName,
                                               nil]
                                  forState:UIControlStateNormal];
        UIBarButtonItem *paddingButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [accessories addObject:plusBarButton];
        [accessories addObject:paddingButton];
    }

    UIBarButtonItem *clearButton = [[UIBarButtonItem alloc] initWithTitle:@"CLEAR" style:UIBarButtonItemStylePlain target:self action:@selector(numberPadClear)];
    [accessories addObject:clearButton];
    
    if (!addPlusMinus){
        UIBarButtonItem *paddingButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        [accessories addObject:paddingButton];
    }
    
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"DONE" style:UIBarButtonItemStylePlain target:self action:@selector(numberPadDone)];
    [accessories addObject:doneButton];

    [numberToolbar setItems:accessories];
    [numberToolbar sizeToFit];
    self.inputAccessoryView = numberToolbar;
}


- (void)numberPadDone {
    [self resignFirstResponder];
}

- (void)numberPadClear {
    self.text = @"";
}

- (void)plusMinusPressed {
    NSString *currentText = self.text;
    if ([currentText hasPrefix:@"-"]) {
        self.text = [currentText substringFromIndex:1];
    }else {
        self.text = [NSString stringWithFormat:@"-%@" ,currentText];
    }
}

- (void)dotPressed {
    NSString *currentText = self.text;
    if ([currentText rangeOfString:@"."].location == NSNotFound) {
        self.text = [currentText stringByAppendingString:@"."];
    }
}



@end
