import _regeneratorRuntime from "@babel/runtime/regenerator";

function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (it) return (it = it.call(o)).next.bind(it); if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

import DataParse from './DataParse'; // DB 本地数据库

var IndexDB = function () {
  // 获取不同内核的indexdb
  var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB; // 数据库

  var dbName = 'SeedsUI_IndexDB';
  var dbTableName = 'SeedsUI_IndexDB_Table';
  var db = null; // 打开仓库, 如果没有此仓库会创建一个

  function open() {
    return new Promise(function (resolve) {
      var request = indexedDB.open(dbName);

      request.onerror = function (event) {
        console.log('SeedsUI IndexDB: 打开数据库报错', event);
        resolve(false);
      };

      request.onsuccess = function (event) {
        db = event.target.result;
        resolve(true);
      }; // 打开数据库不存在创建新仓库时, 则会触发更新事件, 新增一张叫做SeedsUI_IndexDB_Table的表格，主键是id


      request.onupgradeneeded = function (event) {
        db = event.target.result; // 判断SeedsUI_IndexDB_Table表是否存在, 不存在则创建一个

        if (!db.objectStoreNames.contains(dbTableName)) {
          db.createObjectStore(dbTableName, {
            keyPath: 'id'
          });
        }
      };
    });
  } // 默认打开数据库


  open(); // 新增数据

  function add(id, data) {
    if (!id || !data) return null;
    return new Promise( /*#__PURE__*/function () {
      var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(resolve) {
        var openResult, request;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                if (db) {
                  _context.next = 7;
                  break;
                }

                _context.next = 3;
                return open();

              case 3:
                openResult = _context.sent;

                if (openResult) {
                  _context.next = 7;
                  break;
                }

                resolve(false);
                return _context.abrupt("return");

              case 7:
                request = db.transaction([dbTableName], 'readwrite').objectStore(dbTableName).add({
                  id: id,
                  data: data
                });

                request.onsuccess = function () {
                  resolve(true);
                };

                request.onerror = function (event) {
                  console.log('SeedsUI IndexDB: 数据写入失败', event);
                  resolve(false);
                };

              case 10:
              case "end":
                return _context.stop();
            }
          }
        }, _callee);
      }));

      return function (_x) {
        return _ref.apply(this, arguments);
      };
    }());
  } // 更新数据


  function update(id, data) {
    if (!id || !data) return null;
    return new Promise( /*#__PURE__*/function () {
      var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(resolve) {
        var openResult, request;
        return _regeneratorRuntime.wrap(function _callee2$(_context2) {
          while (1) {
            switch (_context2.prev = _context2.next) {
              case 0:
                if (db) {
                  _context2.next = 7;
                  break;
                }

                _context2.next = 3;
                return open();

              case 3:
                openResult = _context2.sent;

                if (openResult) {
                  _context2.next = 7;
                  break;
                }

                resolve(false);
                return _context2.abrupt("return");

              case 7:
                request = db.transaction([dbTableName], 'readwrite').objectStore(dbTableName).put({
                  id: id,
                  data: data
                });

                request.onsuccess = function () {
                  resolve(true);
                };

                request.onerror = function (event) {
                  console.log('SeedsUI IndexDB: 数据更新失败', event);
                  resolve(false);
                };

              case 10:
              case "end":
                return _context2.stop();
            }
          }
        }, _callee2);
      }));

      return function (_x2) {
        return _ref2.apply(this, arguments);
      };
    }());
  } // 移除数据


  function remove(id) {
    if (!id) return null;
    return new Promise( /*#__PURE__*/function () {
      var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(resolve) {
        var openResult, request;
        return _regeneratorRuntime.wrap(function _callee3$(_context3) {
          while (1) {
            switch (_context3.prev = _context3.next) {
              case 0:
                if (db) {
                  _context3.next = 7;
                  break;
                }

                _context3.next = 3;
                return open();

              case 3:
                openResult = _context3.sent;

                if (openResult) {
                  _context3.next = 7;
                  break;
                }

                resolve(false);
                return _context3.abrupt("return");

              case 7:
                request = db.transaction([dbTableName], 'readwrite').objectStore(dbTableName)["delete"](id);

                request.onsuccess = function () {
                  resolve(true);
                };

                request.onerror = function (event) {
                  console.log('SeedsUI IndexDB: 数据删除失败', event);
                  resolve(false);
                };

              case 10:
              case "end":
                return _context3.stop();
            }
          }
        }, _callee3);
      }));

      return function (_x3) {
        return _ref3.apply(this, arguments);
      };
    }());
  } // 删除所有数据


  function removeAll() {
    return new Promise( /*#__PURE__*/function () {
      var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee4(resolve) {
        var openResult, request;
        return _regeneratorRuntime.wrap(function _callee4$(_context4) {
          while (1) {
            switch (_context4.prev = _context4.next) {
              case 0:
                if (db) {
                  _context4.next = 7;
                  break;
                }

                _context4.next = 3;
                return open();

              case 3:
                openResult = _context4.sent;

                if (openResult) {
                  _context4.next = 7;
                  break;
                }

                resolve(false);
                return _context4.abrupt("return");

              case 7:
                request = db.transaction([dbTableName], 'readwrite').objectStore(dbTableName).clear();

                request.onsuccess = function () {
                  resolve(true);
                };

                request.onerror = function (event) {
                  console.log('SeedsUI IndexDB: 表格清除失败', event);
                  resolve(false);
                };

              case 10:
              case "end":
                return _context4.stop();
            }
          }
        }, _callee4);
      }));

      return function (_x4) {
        return _ref4.apply(this, arguments);
      };
    }());
  } // 获取数据


  function _get(id) {
    if (!id || typeof id !== 'string') return null;
    return new Promise( /*#__PURE__*/function () {
      var _ref5 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee5(resolve) {
        var openResult, request;
        return _regeneratorRuntime.wrap(function _callee5$(_context5) {
          while (1) {
            switch (_context5.prev = _context5.next) {
              case 0:
                if (db) {
                  _context5.next = 7;
                  break;
                }

                _context5.next = 3;
                return open();

              case 3:
                openResult = _context5.sent;

                if (openResult) {
                  _context5.next = 7;
                  break;
                }

                resolve(null);
                return _context5.abrupt("return");

              case 7:
                request = db.transaction([dbTableName]).objectStore(dbTableName).get(id);

                request.onsuccess = function () {
                  if (request.result) {
                    resolve(request.result);
                  } else {
                    resolve(null);
                  }
                };

                request.onerror = function (event) {
                  console.log("SeedsUI IndexDB: \u6839\u636Eid: " + id + ", \u83B7\u53D6\u6570\u636E\u5931\u8D25", event);
                  resolve(null);
                };

              case 10:
              case "end":
                return _context5.stop();
            }
          }
        }, _callee5);
      }));

      return function (_x5) {
        return _ref5.apply(this, arguments);
      };
    }());
  } // 获取所有数据


  function _getAll() {
    return new Promise( /*#__PURE__*/function () {
      var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee6(resolve) {
        var openResult, request, list;
        return _regeneratorRuntime.wrap(function _callee6$(_context6) {
          while (1) {
            switch (_context6.prev = _context6.next) {
              case 0:
                if (db) {
                  _context6.next = 7;
                  break;
                }

                _context6.next = 3;
                return open();

              case 3:
                openResult = _context6.sent;

                if (openResult) {
                  _context6.next = 7;
                  break;
                }

                resolve(null);
                return _context6.abrupt("return");

              case 7:
                request = db.transaction([dbTableName]).objectStore(dbTableName).openCursor(); // 构建数据列表: {id: '', data: ''}

                list = [];

                request.onsuccess = function (event) {
                  var cursor = event.target.result;

                  if (cursor) {
                    list.push(cursor.value);
                    cursor["continue"]();
                  } else {
                    resolve(list);
                  }
                };

                request.onerror = function (event) {
                  console.log("SeedsUI IndexDB: \u83B7\u53D6\u6240\u6709\u6570\u636E\u5931\u8D25", event);
                  resolve(null);
                };

              case 11:
              case "end":
                return _context6.stop();
            }
          }
        }, _callee6);
      }));

      return function (_x6) {
        return _ref6.apply(this, arguments);
      };
    }());
  }

  return {
    indexedDB: indexedDB,
    set: function set(key, val) {
      return new Promise( /*#__PURE__*/function () {
        var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee7(resolve) {
          var exists, result;
          return _regeneratorRuntime.wrap(function _callee7$(_context7) {
            while (1) {
              switch (_context7.prev = _context7.next) {
                case 0:
                  _context7.next = 2;
                  return _get(key);

                case 2:
                  exists = _context7.sent;
                  result = null;

                  if (!exists) {
                    _context7.next = 10;
                    break;
                  }

                  _context7.next = 7;
                  return update(key.toString(), DataParse.stringify(val));

                case 7:
                  result = _context7.sent;
                  _context7.next = 13;
                  break;

                case 10:
                  _context7.next = 12;
                  return add(key.toString(), DataParse.stringify(val));

                case 12:
                  result = _context7.sent;

                case 13:
                  resolve(result);

                case 14:
                case "end":
                  return _context7.stop();
              }
            }
          }, _callee7);
        }));

        return function (_x7) {
          return _ref7.apply(this, arguments);
        };
      }());
    },
    get: function get(key) {
      return new Promise( /*#__PURE__*/function () {
        var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee8(resolve) {
          var result;
          return _regeneratorRuntime.wrap(function _callee8$(_context8) {
            while (1) {
              switch (_context8.prev = _context8.next) {
                case 0:
                  _context8.next = 2;
                  return _get(key);

                case 2:
                  result = _context8.sent;

                  if (!(result && result.data)) {
                    _context8.next = 6;
                    break;
                  }

                  resolve(DataParse.parse(result.data));
                  return _context8.abrupt("return");

                case 6:
                  resolve(null);

                case 7:
                case "end":
                  return _context8.stop();
              }
            }
          }, _callee8);
        }));

        return function (_x8) {
          return _ref8.apply(this, arguments);
        };
      }());
    },
    getAll: function getAll() {
      return new Promise( /*#__PURE__*/function () {
        var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee9(resolve) {
          var list, allResult, _iterator, _step, item;

          return _regeneratorRuntime.wrap(function _callee9$(_context9) {
            while (1) {
              switch (_context9.prev = _context9.next) {
                case 0:
                  _context9.next = 2;
                  return _getAll();

                case 2:
                  list = _context9.sent;

                  if (!(Array.isArray(list) && list.length)) {
                    _context9.next = 8;
                    break;
                  }

                  // 列表数据转为键值对数据
                  allResult = {};

                  for (_iterator = _createForOfIteratorHelperLoose(list); !(_step = _iterator()).done;) {
                    item = _step.value;

                    if (item.id) {
                      allResult[item.id] = DataParse.parse(item.data);
                    }
                  }

                  resolve(allResult);
                  return _context9.abrupt("return");

                case 8:
                  resolve(null);

                case 9:
                case "end":
                  return _context9.stop();
              }
            }
          }, _callee9);
        }));

        return function (_x9) {
          return _ref9.apply(this, arguments);
        };
      }());
    },
    remove: remove,
    clear: removeAll
  };
}();

export default IndexDB;