import * as React from "react";
import {Inverter} from "./InverterConnectionPageTypes";
import {createStyles, Theme, withStyles, WithStyles, WithTheme} from "@material-ui/core";
import {InsIvnMonitoredArea} from "../sensors/SensorsPageTypes";
import {createApiRequestStore} from "../../../api/ApiRequestStore";
import Grid from "@material-ui/core/Grid";
import Button from "@material-ui/core/Button";
import {NewInverterDialog} from "./components/NewInverterDialog";
import InverterCard from "./components/InverterCard";
import {SiteDescription} from "../../../common/appRoutes";

const styles = (theme: Theme) =>
    createStyles({
        root: {
            flexGrow: 1,
        },
        paper: {
            padding: theme.spacing(2),
            textAlign: 'center',
            color: theme.palette.text.secondary,
        },
    });


type Props = {
    onSectionChange: (route: SiteDescription) => void
} & WithStyles<typeof styles> & WithTheme


type State = {
    newInverterDialogOpen: boolean
    inverterCards: Inverter[]
    availableMonitoredAreas: InsIvnMonitoredArea[]
}


class InverterPage extends React.Component<Props, State> {
    requestStore = createApiRequestStore();

    readonly state: State = {
        newInverterDialogOpen: false,
        inverterCards: [],
        availableMonitoredAreas: []
    };

    private handleClickOpen = () => {
        this.setState({
            newInverterDialogOpen: true
        })
    };

    private handleClose = () => {
        this.setState({
            newInverterDialogOpen: false
        })
    };

    private handleSubmit = (newInverter: Inverter) => {
        this.requestStore.createNewInverter(Object.assign(newInverter))
            .then(response => {
                if (response) {
                    this.handleClose();
                    this.loadInverters();
                }
            }).catch((error) => {
            alert("something went wrong and new inverter was not created.")
        });
    };

    private loadInverters = () => {
        this.requestStore.loadInverters()
            .then(response => {
                this.setState({
                    ...this.state,
                    inverterCards: response.inverters,
                    availableMonitoredAreas: response.availableMonitoredAreas
                })
            })
            .catch(error => {
                alert("No inverters loaded for current user.")
            })
    };

    private handleUpdate = (inverter: Inverter) => {
        this.requestStore.updateInverter(Object.assign(inverter))
            .then(response => {
                this.loadInverters()
            })
            .catch(error => {
                alert("Could not update inverter.")
            })
    };

    componentDidMount() {
        this.loadInverters()
    }

    render() {
        console.log("loaded inverters: ", this.state.inverterCards);
        return <div className={this.props.classes.root}>
            <Grid container spacing={3}>
                <Grid item xs={12}>
                    <div>
                        <Button variant="outlined" color="primary" onClick={this.handleClickOpen}>
                            New Inverter
                        </Button>
                        <NewInverterDialog handleSubmit={this.handleSubmit}
                                           dialogOpen={this.state.newInverterDialogOpen}
                                           handleClose={this.handleClose}/>
                    </div>
                </Grid>
                {this.state.inverterCards.map((value, index) => <InverterCard key={value.id} inverter={value}
                                                                              availableMonitoredAreas={this.state.availableMonitoredAreas}
                                                                              cardIndex={index}
                                                                              handleUpdate={this.handleUpdate}
                                                                              onSectionChange={this.props.onSectionChange}
                />)}
            </Grid>
        </div>
    }


}


export default withStyles(styles, {withTheme: true})(InverterPage);