//
//  TBLRNTClassicPage.m
//  TaboolaReactNativePlugin4x
//
//  Created by Daniel Frimet on 11/05/2025.
//

#import "TBLRNTClassicPage.h"
#import "TBLRNTClassicUnit.h"
#import "TBLRNTUtils.h"

@interface TBLRNTClassicPage ()
@property(nonatomic, strong, readwrite) NSString *tblRNTClassicPageId;
@property(nonatomic, strong) NSMutableDictionary *unitsMap;
@end

/**
 * This class wraps the TBLClassicPage and saves a reference for each created
 * TBLClassicUnit via the build function. It also offers a getter to retrieve a
 * unit using its UnitHashCode ID.
 */
@implementation TBLRNTClassicPage

- (instancetype)initWithPageType:(NSString *)pageType
                         pageUrl:(NSString *)pageUrl
                        delegate:(id<TBLClassicPageDelegate>)delegate {
  self = [super initWithPageType:pageType
                         pageUrl:pageUrl
                        delegate:delegate
                      scrollView:nil];
  if (self) {
    self.tblRNTClassicPageId = [TBLRNTUtils generateHashStringForObject:self];
    self.unitsMap =
        [NSMutableDictionary<NSString *, TBLClassicUnit *> dictionary];
  }
  return self;
}

- (nullable NSString *)build:(NSString *)placementName
                                mode:(NSString *)mode {
  if (!placementName || !mode) {
    NSLog(@"Error: Invalid placementName or mode");
    return nil;
  }


  TBLRNTClassicUnit *tblRntClassicUnit = [[TBLRNTClassicUnit alloc] init];
  
  if (!tblRntClassicUnit) {
    NSLog(@"Error: Failed to create TBLRNTClassicUnit");
    return nil;
  }

  // Enrich the empty unit and create it using the valid taboola approach via
  // addUnit to page
  [self addUnit:tblRntClassicUnit placementName:placementName mode:mode];

  NSString *unitHashCode = [tblRntClassicUnit getUnitHashCode];
  [self storeTBLClassicUnitOnMap:tblRntClassicUnit];

  return unitHashCode;
}

- (void)storeTBLClassicUnitOnMap:(TBLRNTClassicUnit *)tblRntClassicUnit {
  if (!tblRntClassicUnit) {
    NSLog(@"Error: Attempting to store nil classic unit");
    return;
  }

  NSString *tblRntClassicUnitHashCode = [tblRntClassicUnit getUnitHashCode];

  if ([self.unitsMap objectForKey:tblRntClassicUnitHashCode]) {
    NSLog(@"Warning: Replacing existing classic unit for key: %@",
          tblRntClassicUnitHashCode);
  }

  [self.unitsMap setObject:tblRntClassicUnit forKey:tblRntClassicUnitHashCode];
}

- (TBLRNTClassicUnit *)getClassicUnit:(NSString *)hashCodeId {
  return [self.unitsMap valueForKey:hashCodeId];
}

@end
