import React from 'react';
import './App.scss';
import UserStatsMockService from "./mock/UserStatsMockService";
import UserStatsService from "./services/UserStatsService";
import {findDOMNode} from "react-dom";
import TableEntry from "./models/TableEntry";
import UserList from './components/UserList/UserList';
import ErrorContainer from './components/ErrorContainer/ErrorContainer';
import Footer from './components/Footer/Footer';
import Header from './components/Header/Header';

interface State {
  error?: string,
  loading: boolean,
  users: TableEntry[],
  mock: TableEntry[]
}

export default class App extends React.Component {

  private apiService: UserStatsService = new UserStatsService();
  private mockService = new UserStatsMockService();

  state: State;

  constructor(props: Readonly<{}>) {
    super(props);
    this.state = {
        error: undefined,
        loading: false,
        users: [],
        mock: this.mockService.getStatsWithoutPromise()
    }
  }

  componentWillMount() {
    this.fetchData();
  }

  private fetchData() {
    this.setState({ loading: true })
    this.apiService.getStats()
    .then(data => this.setState({
      loading: false,
      users: data
    }))
  }

  // componentDidMount() {
    // this.setState({loading: false, mock: this.mockService.getStatsWithoutPromise()});
    // this.apiService.getStats()
    //   .then(data => this.setState({
    //     isLoaded: true,
    //     users: data
    //   }))
    //   .catch(error => {
    //     error.response.json()
    //       .then((err: any) => this.setState({
    //         isLoaded: true,
    //         error: err.error
    //       }))
    //   });
  // }

  componentDidUpdate() {
    const element = findDOMNode(this);
    if (element != null) {
      window.scrollTo(0, 0);
    }
  }

  render() {
    return (
      <div className="App">
        <Header />
        {/* { this.state.error != null ? <p className="error-message"> { this.state.error } Please try again later!</p> : null} */}
        {
          (!this.state.error && this.state.loading)
          ? <UserList users={this.state.mock} />
          : <UserList users={this.state.users} />
        }
        {
          this.state.error && <ErrorContainer message={this.state.error} />
        }
        <Footer />
      </div>
    );
  }
}
