/* @flow */

import React from 'react-native';
import type { Embed } from './oEmbedTypes';

const {
	AsyncStorage
} = React;

let data;

export default {
	async _readData(): Promise<void> {
		const dataString = await AsyncStorage.getItem('oembed_storage');

		if (dataString) {
			data = JSON.parse(dataString);
		} else {
			data = [];
		}
	},

	_findItem(key: string): ?Embed {
		for (let i = 0, l = data.length; i < l; i++) {
			if (data[i] && data[i].url === key) {
				return data[i].json;
			}
		}

		return null;
	},

	async set(url: string, json: Embed): Promise<void> {
		const item = await this.get(url);

		if (item) {
			item.json = json;
		} else {
			data.push({
				url,
				json
			});
		}

		if (data.length >= 100) {
			data.splice(0, 10);
		}

		return AsyncStorage.setItem('oembed_storage', JSON.stringify(data));
	},

	async get(url: string): Promise<?Embed> {
		if (!data) {
			await this._readData();
		}

		return this._findItem(url);
	}

};

@@ -17,31 +17,58 @@
 ort 
-React from 'react-nativ
+PersistentStorage from '../../lib/PersistentStorag
 e';%0A
@@ -122,33 +122,55 @@
 nst 
-%7B%0A%09Async
+oEmbed
 Storage
-%0A%7D
  = 
-React
+new PersistentStorage('oembed')
 ;%0A%0Al
@@ -259,21 +259,22 @@
 = await 
-Async
+oEmbed
 Storage.
@@ -282,30 +282,20 @@
 etItem('
-oembed_storage
+data
 ');%0A%0A%09%09i
@@ -809,13 +809,14 @@
 urn 
-Async
+oEmbed
 Stor
@@ -832,22 +832,12 @@
 em('
-oembed_storage
+data
 ', J

use PersistentStorage for oEmbed