import * as React from 'react'
import { connect } from 'react-redux'
import {ThemeNotifier} from './theme-notifier'
import { THEME_REDUCER_KEY } from './constants'
import { StyleProviderProps, StyleProviderComponentProps, StyleContext } from './interfaces'
import { object } from 'prop-types'

class _StyleProvider extends React.Component<StyleProviderComponentProps, any> {

    public static childContextTypes = {
        themeNotifier: object,
    }

    public themeNotifier: ThemeNotifier

    constructor(props: any, state: any) {
        super(props, state)
        this.themeNotifier = new ThemeNotifier(this.props.theme)
    }

    /**
     * Make the theme notifier available via React context
     */
    public getChildContext() {
        return { themeNotifier: this.themeNotifier }
    }

    /**
     * Let the theme notifier know that it should update all its subscribers
     *
     * @param nextProps
     */
    public componentWillReceiveProps(nextProps: StyleProviderComponentProps) {
        this.themeNotifier.setTheme(nextProps.theme)
    }

    public render() {
        return this.props.children as JSX.Element
    }
}

const mapStateToProps = (state: any, ownProps: StyleProviderProps) => ({
    theme: state[THEME_REDUCER_KEY],
})

const mapDispatchToProps = {}

export const StyleProvider = connect(mapStateToProps, mapDispatchToProps)(_StyleProvider)