import React, {Component} from 'react';
import {Input, Spin} from 'antd';
import GraphiQL from "graphiql";
import fetch from "isomorphic-fetch";
import gql from "graphql-tag";
import {Query} from "react-apollo";

import {GET_PROJECT} from "../../../../gql";

class Graphql extends Component {
    constructor(props) {
        super(props);
        this.state = {
            api: props.api,
            show: props.api !== ''
        };
    };

    componentWillReceiveProps(next) {
        this.setState({
            api: next.api,
            show: next.api !== ''
        })
    }

    graphQLFetcher = (graphQLParams) => {
        // 已经存在的 magazine api， 设想: 用户生成 schema，返回 api 自动替换这里
        return fetch(this.state.api, {
            method: 'post',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(graphQLParams),
        }).then(response => response.json());
    };

    render() {
        let projectID = this.props.projectID ? this.props.projectID : 'ecommerce_projectID';
        return (
            <Query query={gql(GET_PROJECT)} variables={{id: projectID}}>
                {
                    ({loading, error, data}) => {
                        if (loading) {
                            return <Spin style={{marginLeft: 3}}/>
                        }
                        if (error) {
                            return 'error!';
                        }
                        let group = data.project_by_id.apiGWGroup_id;
                        if (this.state.api === '') {
                            let domain = group.userDomain? group.userDomain : group.defaultDomain;
                            this.setState({
                                // 多路径没做
                                api: group.frontType.slice(0, 4) + '://' + domain + '/graphql',
                                show: true
                            })
                        }
                        return (
                            <div>
                                <Input
                                    style={{marginTop: 10}}
                                    addonBefore="POST"
                                    defaultValue={this.state.api}
                                    onChange={(e) => {
                                        this.setState({api: e.target.value})
                                    }}/>
                                {
                                    this.state.show?
                                        <GraphiQL fetcher={this.graphQLFetcher}/>
                                        :
                                        ''
                                }
                            </div>
                        )
                    }
                }
            </Query>
        )
    }
}

export default Graphql;