import React, {Component} from 'react';
import axios from 'axios';
import {BackTop, Tabs, Button, Spin} from 'antd';
import saveAs from 'file-saver';
import beautify from 'js-beautify';

import './index.css';

const TabPane = Tabs.TabPane;
axios.defaults.withCredentials = true;

class GenerateJs extends Component {
    constructor(props) {
        super(props);
        this.state = {
            schemaID:props.schemaID,
            schemaName:props.schemaName,
            graphqlJs:'',
            show: false
        };
    }

    componentDidMount() {
        this._isMounted = true;
        let requestUrl = 'http://123.206.193.98:8999/graphql/genjs';
        let _this = this;
        let {schemaID} = this.state;
        axios.get(`${requestUrl}?schema=${schemaID}`)
            .then((res) => {
                if(this._isMounted){
                    if (res.data !== '') {
                        // console.log('js res', res.data);
                        let graphqlJs = beautify(res.data, { indent_size: 2, space_in_empty_paren: true });
                        // console.log('beautify graphqlJs',graphqlJs);
                        _this.setState({
                            graphqlJs,
                            show: true
                        });
                    } else {
                        _this.setState({
                            show: true
                        })
                    }
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }

    componentWillReceiveProps(next) {
        this.setState({
            schemaID: next.schemaID,
        });
    }

    componentDidUpdate() {
        this._isMounted = true;
        let requestUrl = 'http://123.206.193.98:8999/graphql/genjs';
        let _this = this;
        let {schemaID} = this.state;
        axios.get(`${requestUrl}?schema=${schemaID}`)
            .then((res) => {
                if(this._isMounted){
                    if (res.data !== '') {
                        // console.log('js res', res.data);
                        let graphqlJs = beautify(res.data, { indent_size: 2, space_in_empty_paren: true });
                        // console.log('beautify graphqlJs',graphqlJs);
                        _this.setState({
                            graphqlJs,
                            show: true
                        });
                    } else {
                        _this.setState({
                            show: true
                        })
                    }
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }

    componentWillUnmount() {
        this._isMounted = false;
    }

    saveFile =()=>{
        let {schemaName,graphqlJs} = this.state;
        let blob = new Blob([graphqlJs], {type: "text/plain;charset=utf-8"});
        saveAs(blob, `${schemaName}_graphql.js`);
    };

    render() {
        let {graphqlJs} = this.state;
        let queryList = [];
        let mutationList = [];
        let graphqlJsList = beautify(graphqlJs, { indent_size: 2, space_in_empty_paren: true });
        // console.log('beautify graphqlJs',graphqlJsList);
        graphqlJsList.split("}\n}\n").forEach((item) => {
            if (item.indexOf('query')>-1) queryList.push(item+"}\n}\n");
            else mutationList.push(item+"}\n}\n");
        });
        // console.log('queryList',queryList);
        // console.log('mutationList',mutationList);
        return (
            <div>
                <Tabs
                    defaultActiveKey="query"
                    tabPosition="left"
                >
                    <TabPane tab="Query" key="query">
                        <div className='download-button'>
                            <Button type="primary" style={{float:'right'}} onClick={()=>this.saveFile()}>Download</Button>
                        </div>
                        <br/>
                        {this.state.show ?
                            <GraphqlJs graphqlList={queryList}/>
                            :
                            <Loading/>
                        }
                    </TabPane>

                    <TabPane tab="Mutation" key="mutation">
                        <div className='download-button'>
                            <Button type="primary" style={{float:'right'}} onClick={()=>this.saveFile()}>Download</Button>
                        </div>
                        <br/>
                        {this.state.show ?
                            <GraphqlJs graphqlList={mutationList}/>
                            :
                            <Loading/>
                        }
                    </TabPane>
                </Tabs>
                <div>
                    <BackTop />
                </div>
            </div>
        )
    }
}

export default GenerateJs;

class GraphqlJs extends Component {
    render() {
        return (
            <div>
                 <pre>
                     <code>
                         {this.props.graphqlList}
                     </code>
                 </pre>
            </div>
        );
    }
}

class Loading extends Component {
    render() {
        return (
            <div style={{width: '100%', height: window.innerHeight - 164}}>
                <Spin
                    tip={'loading...'}
                    style={{
                        position: 'relative',
                        top: '50%',
                        left: '50%',
                        transform: 'translate(-50%,-50%)'
                    }}/>
            </div>
        );
    }
}