import React, { ComponentType, Component } from "react";

interface PageItem {
  Component: ComponentType<any>;
  props?: any;
}

interface PageCtrlState {
  pages: PageItem[];
}

export class PageCtrl extends Component<{}, PageCtrlState> {
  state = {
    pages: [],
  };

  static changePage: (Component: ComponentType<any>, props?: any) => void = null;
  static backPage: () => void = null;
  static replacePage: (Component: ComponentType<any>, props?: any) => void = null;

  componentDidMount() {
    PageCtrl.changePage = this.changePage;
    PageCtrl.backPage = this.backPage;
    PageCtrl.replacePage = this.replacePage;
  }

  componentWillUnmount() {
    PageCtrl.changePage = null;
    PageCtrl.backPage = null;
    PageCtrl.replacePage = null;
  }

  changePage = (Component: ComponentType<any>, props: any = {}) => {
    const pages = this.state.pages;
    pages.push({Component, props});
    this.setState({pages});
  };

  backPage = () => {
    const pages = this.state.pages;
    if (pages.length > 1) {
      pages.pop();
      this.setState({pages});
    }
  };

  replacePage = (Component: ComponentType<any>, props: any = {}) => {
    const pages = this.state.pages;
    if (pages.length > 0) {
      pages[pages.length - 1] = { Component, props };
      this.setState({ pages });
    } else {
      this.changePage(Component, props);
    }
  }

  render() {
    const { pages } = this.state;
    if (!pages.length) return null;
    const curPage = pages[pages.length - 1];
    return <curPage.Component {...curPage.props}/>;
  }
}
