import React from 'react';
import superagent from 'superagent';
import msgpack from 'msgpack-lite';
import {Button, Header, Label, Table, Image, Form} from 'semantic-ui-react';

import NetworkWrapper from './NetworkWrapper.jsx';

class Redis extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            pattern: null,
            loading: false,
            redisKeys: [],
            expandedRedisKeys: {}
        };
    }

    onChange(e, { name, value }) {
        this.setState({ [name]: value })
    }

    async onSubmit(e) {
        e.preventDefault();
        this.setState({ loading: true });
        try {
            const res = await superagent.post(`/cloud/admin/network/redis`).send({ pattern: this.state.pattern }).accept('json');
            console.log(res.body);
            this.setState({ loading: false, redisKeys: res.body, expandedRedisKeys: {} });
        } catch (e) {
            console.log(e);
            this.setState({ loading: false, redisKeys: [], expandedRedisKeys: {} });
        }
    }

    async onExpand(redisKey) {
    }

    async onRedisKeyClick(redisKey, e) {
        e.preventDefault();
        
        this.setState({ loading: true });
        try {
            const res = await superagent.post(`/api/network/redis`).send({ key: redisKey }).accept('json');
            const { expandedRedisKeys } = this.state;

            let redisValue = {};
            if (res.body.data) {
                redisValue = msgpack.decode(Buffer.from(res.body.data, 'base64'));
                redisValue = JSON.stringify(redisValue, null, 4);
            } else {
                redisValue = JSON.stringify(res.body, null, 4);
            }
            expandedRedisKeys[redisKey] = redisValue;
            this.setState({ loading: false, expandedRedisKeys });
        } catch (e) {
            console.log(e);
            this.setState({ loading: false });
        }
    }

    renderRedisKey(redisKey) {
        let value = (this.state.expandedRedisKeys[redisKey]) && <pre style={{whiteSpace: 'pre-wrap'}}>
            {this.state.expandedRedisKeys[redisKey]}
        </pre>;

        return (
            <Table.Row>
                <Table.Cell width={4}>
                    <a href="#" onClick={this.onRedisKeyClick.bind(this, redisKey)}>{redisKey}</a>
                </Table.Cell>
                <Table.Cell width={12} >
                    <div style={{overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap"}}>
                        {value}
                    </div>
                </Table.Cell>
            </Table.Row>
        )
    }

    render() {
        return (
            <NetworkWrapper title="Redis" loading={this.state.loading}>
                <Form size="normal" onSubmit={this.onSubmit.bind(this)}>
                    <Form.Group widths="equal">
                        <Form.Input icon="user" label="Search redis database" autoComplete="off" placeholder="Enter a search pattern" 
                            name="pattern" onChange={this.onChange.bind(this)} focus />
                        <Form.Button icon="right arrow" labelPosition="right" content="Search Redis" type="submit" />
                    </Form.Group>
                </Form>
                <Table compact celled>
                    
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell width={2}>Key</Table.HeaderCell>
                            <Table.HeaderCell width={1}>Value</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>
                    
                    <Table.Body>
                    {this.state.redisKeys.map(redisKey => {
                        return this.renderRedisKey(redisKey);
                    })}
                    </Table.Body>
                </Table>
            </NetworkWrapper>
        );
    }
}

export default Redis;
