import * as querystring from 'querystring';
import { History } from '../services/History';
import Base from './base';

export default class PathStore extends Base {
  initState() {
    this.locationList = [window.location.pathname];
    this.isCallBack = false;
    return {
      isCallBack: this.isCallBack,
      location: window.location.pathname,
      query: querystring.parse(window.location.search.replace('?', '')),
    };
  }

  init() {
    History.listen(this.locationChange.bind(this));
  }

  locationPush(location) {
    this.isCallBack = false;
    this.locationList.push(location.pathname);
  }

  locationPop() {
    if (this.locationList.length > 0) {
      this.locationList.pop();
      this.isCallBack = true;
    }
  }

  locationReplace(location) {
    this.locationList.pop();
    this.isCallBack = false;
    this.locationList.push(location.pathname);
  }

  locationChange(location, action) {
    if (action === 'POP') {
      this.locationPop(location);
    } else if (action === 'REPLACE') {
      this.locationReplace(location);
    } else {
      this.locationPush(location);
    }
    this.updateLocation(location);
  }

  updateLocation(location) {
    this.setState({
      location: location.pathname,
      isCallBack: this.isCallBack,
      query: querystring.parse(window.location.search.replace('?', '')),
    });
  }
}

export const Path = new PathStore('path');
