import React, { Component } from 'react';
import Context from './../FreactalStoreContext';
import FreactalStore from '../FreactalStore/FreactalStore';
import StateContext from './../FreactalStateContext';

export default class ProviderContainer extends Component {
  static contextType = Context;

  constructor(props) {
    super(props);
    this.state = this.props.initializer(props);
  }

  componentDidUpdate() {
    this.store.refreshCombinedState();
  }

  componentDidMount() {
    console.log('context', this.context);
  }

  render() {
    if (!this.store) {
      if (this.context) {
        console.log('context with parent', this.props);
      } else {
        console.log('context without parent', this.props);
      }
      this.store = new FreactalStore({
        ...this.props,
        component: this,
        parent: this.context,
      });
    }

    return (
      <Context.Provider value={this.store}>
        <StateContext.Provider value={this.store.combinedState}>
          {this.props.children || ''}
        </StateContext.Provider>
      </Context.Provider>
    );
  }
}
