//
//  NetworkManager.m
//  HelloWorld
//
//  Created by JohnnyChung on 01/12/2016.
//  Copyright © 2016 Facebook. All rights reserved.
//

#import "DBManager.h"
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#define WeakObj(o) autoreleasepool{} __weak typeof(o) o##Weak = o;

@implementation DBManager

RCT_EXPORT_MODULE();


RCT_EXPORT_METHOD(saveLocally:(NSString *)key Withvalue:(NSString *)value callback:(nonnull RCTResponseSenderBlock)callback){
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:value forKey:[NSString stringWithFormat:@"user_%@", key]];
	if([defaults synchronize]){
		callback(@[]);
	}else{
    @WeakObj(self);
		callback(@[[selfWeak getErrorDict:201 withmessage:@"Fail_to_save"]]);
	}
	
}

RCT_EXPORT_METHOD(saveDictLocally:(NSString *)key Withvalue:(NSDictionary *)value callback:(nonnull RCTResponseSenderBlock)callback){
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
	[defaults setObject:value forKey:[NSString stringWithFormat:@"user_%@", key]];
	if([defaults synchronize]){
		callback(@[[NSNull null]]);
	}else{
    @WeakObj(self);
		callback(@[[selfWeak getErrorDict:201 withmessage:@"Fail_to_save"]]);
	}
}


RCT_EXPORT_METHOD(readLocally:(NSString *)key callback:(nonnull RCTResponseSenderBlock)callback){
	NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  if([defaults objectForKey:[NSString stringWithFormat:@"user_%@", key]]){
    callback(@[[NSNull null], [defaults objectForKey:[NSString stringWithFormat:@"user_%@", key]]]);
  }else{
    callback(@[[NSNull null], @""]);
    }
}


- (NSString *) addRequestKey {
  NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
  NSArray<NSNumber *> *arr = [defaults objectForKey:@"request"];
  int request_id;
  if(arr){
    NSNumber *number = [arr lastObject];
    request_id = [number intValue]  + 1;
    NSLog(@"request_id = %d", request_id);
  }else{
    NSLog(@"init request_id = 0 ");
    arr = [[NSArray alloc]init];
    request_id = 0;
  }
  [defaults setObject:[arr arrayByAddingObject:[NSNumber numberWithInt:request_id]] forKey:@"request"];
  [defaults synchronize];
   return [NSString stringWithFormat:@"request_%d", request_id];
}

- (NSDictionary *) getErrorDict:(int)code withmessage:(NSString *)message{
	NSDictionary *dict =  [NSDictionary dictionaryWithObjectsAndKeys:@"code", code, @"message", message, nil];
  return dict;
}




@end
