//
//  PieChartView.cpp
//  react-native-charts
//
//  Created by Peter Vu on 12/01/2023.
//

#import "PieChartView.h"

#import <react/renderer/components/RNChartsViewSpec/ComponentDescriptors.h>
#import <react/renderer/components/RNChartsViewSpec/EventEmitters.h>
#import <react/renderer/components/RNChartsViewSpec/Props.h>
#import <react/renderer/components/RNChartsViewSpec/RCTComponentViewHelpers.h>

#import "RCTFabricComponentsPlugins.h"
#import "RNCharts-Swift.h"

using namespace facebook::react;

@interface RNPieChartView () <RCTRNPieChartViewViewProtocol>

@end

@implementation RNPieChartView {

	PieChartView * _view;
}

+ (ComponentDescriptorProvider)componentDescriptorProvider
{

	return concreteComponentDescriptorProvider<RNPieChartViewComponentDescriptor>();
}

- (instancetype)initWithFrame:(CGRect)frame
{
  if (self = [super initWithFrame:frame]) {
	static const auto defaultProps = std::make_shared<const RNPieChartViewProps>();
	_props = defaultProps;

	_view = [[PieChartView alloc] init];
	  _view.chartDescription.enabled = NO;
	  _view.drawEntryLabelsEnabled = NO;
	  _view.transparentCircleRadiusPercent = 0;
	  _view.maxAngle = 360;
	  _view.highlightPerTapEnabled = NO;
	  _view.legend.enabled = NO;
	  _view.rotationAngle = -90;
	  _view.rotationEnabled = NO;

	self.contentView = _view;
  }

  return self;
}

- (void)updateProps:(Props::Shared const &)props oldProps:(Props::Shared const &)oldProps
{
	const auto &oldViewProps = *std::static_pointer_cast<RNPieChartViewProps const>(_props);
	const auto &newViewProps = *std::static_pointer_cast<RNPieChartViewProps const>(props);
	
	NSMutableArray<NSString*>* pieColorsStrings = [[NSMutableArray alloc] init];
    
    std::string dataJsonString = newViewProps.seriesJsonData.series.data;
    NSString *convertedDataJsonString = [NSString stringWithUTF8String:dataJsonString.c_str()];
        
    NSError *error;
    NSDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:[convertedDataJsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
        
    NSArray *dataValuesArray = [parsedData allValues];
    
    NSMutableArray<PieChartDataEntry*>* entries = [[NSMutableArray alloc] init];
    
    for (int dataSetIndex = 0; dataSetIndex < [dataValuesArray count]; dataSetIndex++) {
        NSDictionary *dataEntryValue = dataValuesArray[dataSetIndex];
        NSString *colorStringValue = dataEntryValue[@"color"];
        NSNumber *yValue = dataEntryValue[@"y"];
        PieChartDataEntry* entry = [[PieChartDataEntry alloc] initWithValue:yValue.doubleValue];
        [pieColorsStrings addObject: colorStringValue];
        [entries addObject:entry];
    }
    
//	NSMutableArray<PieChartDataEntry*>* entries = [[NSMutableArray alloc] init];
//	for (auto it = begin (newViewProps.seriesData.series.data); it != end (newViewProps.seriesData.series.data); ++it) {
//		PieChartDataEntry* entry = [[PieChartDataEntry alloc] initWithValue:it->y];
//		[pieColorsStrings addObject: [[NSString alloc] initWithUTF8String:it->color.c_str()]];
//		[entries addObject:entry];
//	}
	
	if (newViewProps.seriesData.colors.size() > 0) {
		pieColorsStrings = [[NSMutableArray alloc] init];
		for (auto it = begin (newViewProps.seriesData.colors); it != end (newViewProps.seriesData.colors); ++it) {
			[pieColorsStrings addObject: [[NSString alloc] initWithUTF8String:it->c_str()]];
		}
	}
	
	NSMutableArray<UIColor*>* pieColors = [NSMutableArray array];
	for (NSString* colorString in pieColorsStrings) {
		[pieColors addObject:[self hexStringToColor:colorString]];
	}
	
	_view.holeRadiusPercent = newViewProps.plotOptions.pie.innerSize / 100;
	_view.drawHoleEnabled = YES;
	PieChartDataSet* dataSet = [[PieChartDataSet alloc] initWithEntries:entries];
	dataSet.colors = pieColors;
	dataSet.drawValuesEnabled = NO;
	dataSet.selectionShift = 0;
	dataSet.sliceSpace = 2;
	
	PieChartData* data = [[PieChartData alloc] initWithDataSet:dataSet];
	_view.data = data;

	[super updateProps:props oldProps:oldProps];
}

Class<RCTComponentViewProtocol> RNPieChartViewCls(void)
{
	return RNPieChartView.class;
}

- hexStringToColor:(NSString *)stringToConvert
{
	NSString *noHashString = [stringToConvert stringByReplacingOccurrencesOfString:@"#" withString:@""];
	NSScanner *stringScanner = [NSScanner scannerWithString:noHashString];
	
	unsigned hex;
	if (![stringScanner scanHexInt:&hex]) return nil;
	int r = (hex >> 16) & 0xFF;
	int g = (hex >> 8) & 0xFF;
	int b = (hex) & 0xFF;
	
	return [UIColor colorWithRed:r / 255.0f green:g / 255.0f blue:b / 255.0f alpha:1.0f];
}

@end
