// Copyright 2014 Flávio Ribeiro <flavio@bem.tv>.
// All rights reserved.
// Use of this source code is governed by a Apache
// license that can be found in the LICENSE file.

var Settings = require("./settings")
var _ = require("underscore")
var log = require('./log').getInstance()

class Storage {
  constructor() {
    this.keys = []
    this.chunks = {}
  }

  setItem(key, value) {
    if (_.has(this.chunks, key)) {
      log.warn("already have this chunk on storage: " + key)
    } else {
      this.keys.push(key)
      this.chunks[key] = value
      this.updateSize()
    }
  }

  get size() {
    return this.keys.length
  }

  updateSize() {
    if (this.size > Settings.maxStorageChunks) {
      this.removeOlderItem()
    }
  }

  removeOlderItem() {
    var key = this.keys.splice(0, 1)[0]
    delete this.chunks[key]
  }

  getItem(key) {
    return this.chunks[key];
  }

  contain(key) {
    return _.contains(this.keys, key)
  }
}

Storage.getInstance = function() {
  if (this._instance === undefined) {
    this._instance = new this();
  }
  return this._instance;
}

module.exports = Storage


@@ -377,24 +377,78 @@
 y, value) %7B%0A
+    var normalizedKey = key.match(/(.*.ts)%5C??.*?/)%5B1%5D%0A
     if (_.ha
@@ -462,17 +462,27 @@
 chunks, 
-k
+normalizedK
 ey)) %7B%0A 
@@ -536,17 +536,27 @@
 ge: %22 + 
-k
+normalizedK
 ey)%0A    
@@ -585,17 +585,27 @@
 ys.push(
-k
+normalizedK
 ey)%0A    
@@ -618,17 +618,27 @@
 .chunks%5B
-k
+normalizedK
 ey%5D = va
@@ -934,32 +934,86 @@
  getItem(key) %7B%0A
+    var normalizedKey = key.match(/(.*.ts)%5C??.*?/)%5B1%5D%0A
     return this.
@@ -1019,17 +1019,27 @@
 .chunks%5B
-k
+normalizedK
 ey%5D;%0A  %7D
@@ -1053,24 +1053,78 @@
 tain(key) %7B%0A
+    var normalizedKey = key.match(/(.*.ts)%5C??.*?/)%5B1%5D%0A
     return _
@@ -1144,17 +1144,27 @@
 s.keys, 
-k
+normalizedK
 ey)%0A  %7D%0A

remove querystring from segment url