import Router from 'next/router';
import { parse, stringify } from 'qs';

const queue = {
  items: [],
  isInProcessing: false,
  runProcessing: () => {
    queue.isInProcessing = true;
    if (queue.items.length) {
      const qItems = queue.items.reverse();
      const qItem = qItems.pop();

      // need parse next router to object as we do in prev version with history
      const queryParsedFromNextRouterQuery = parse(stringify(Router.query));

      const url = `${qItem.pathname}?${stringify(qItem.getQuery(queryParsedFromNextRouterQuery), { encode: false })}`;

      const promise = new Promise((resolve, reject) => {
        const currentPathName = Router.pathname;

        if (currentPathName === qItem.pathname) {
          Router.push(url, undefined, { shallow: true }).then(resolve).catch(reject);
        } else {
          resolve();
        }
      });

      promise.then(queue.runProcessing).catch(() => {
        queue.items = [];
        queue.isInProcessing = false;
      });
    } else {
      queue.isInProcessing = false;
    }
  },
};

export default queue;
