#import <Foundation/Foundation.h>

@interface Abbreviation : NSObject
@property (nonatomic, assign) double threshold;
@property (nonatomic, assign) double multiplier;
@property (nonatomic, copy) NSString *suffix;

- (instancetype)initWithThreshold:(double)threshold multiplier:(double)multiplier suffix:(NSString *)suffix;

@end

@implementation Abbreviation

- (instancetype)initWithThreshold:(double)threshold multiplier:(double)multiplier suffix:(NSString *)suffix {
	self = [super init];
	if (self) {
		_threshold = threshold;
		_multiplier = multiplier;
		_suffix = suffix;
	}
	return self;
}

@end

@interface NSNumberFormatter (Abbreviation)

+ (NSNumberFormatter *)abbreviationFormatterForNumber:(NSInteger)number;

@end

@implementation NSNumberFormatter (Abbreviation)

+ (NSNumberFormatter *)abbreviationFormatterForNumber:(NSInteger)number {
	NSArray<Abbreviation *> *abbreviations = @[
		[[Abbreviation alloc] initWithThreshold:0.0 multiplier:1.0 suffix:@""],
		[[Abbreviation alloc] initWithThreshold:1000.0 multiplier:0.001 suffix:@"K"],
		[[Abbreviation alloc] initWithThreshold:1000000.0 multiplier:0.000001 suffix:@"M"],
		[[Abbreviation alloc] initWithThreshold:100000000.0 multiplier:0.000000001 suffix:@"B"]
	];

	double startValue = fabs((double)number);
	Abbreviation *abbreviation;
	Abbreviation *prevAbbreviation = abbreviations[0];

	for (Abbreviation *tmpAbbreviation in abbreviations) {
		if (startValue < tmpAbbreviation.threshold) {
			break;
		}
		prevAbbreviation = tmpAbbreviation;
	}

	abbreviation = prevAbbreviation;

	NSNumberFormatter *numFormatter = [[NSNumberFormatter alloc] init];
	numFormatter.positiveSuffix = abbreviation.suffix;
	numFormatter.negativeSuffix = abbreviation.suffix;
	numFormatter.allowsFloats = YES;
	numFormatter.multiplier = @(abbreviation.multiplier);
	numFormatter.minimumIntegerDigits = 1;
	numFormatter.minimumFractionDigits = 0;
	numFormatter.maximumFractionDigits = 1;

	return numFormatter;
}

@end
