import React from "react";
import superagent from "superagent";
import _ from "lodash";

import AccountsWrapper from "./AccountsWrapper.jsx";
import AccountSearchResultsTable from "./AccountSearchResultsTable.jsx";

import {
    Segment,
    Header,
    Image,
    Button,
    Form } from "semantic-ui-react"

class AccountSearch extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            query: {},
            results: [],
            loading: false
        };
    }

    async componentDidMount() {
        try {
            const params = new URLSearchParams(window.location.search);
            const query = {};
            for (const [key, value] of params.entries()) {
                query[key] = value;
            }
            this.setState({ query }, async () => {
                await this.onAccountSearch();
            });

        } catch (e) {
            console.log(e);
        }
    }

    getUrlSearchParams() {
        const queryString = new URLSearchParams();

        if (this.state.query) {
            for (const [key, value] of Object.entries(this.state.query)) {
                if (value === "" || value === null) continue;
                queryString.append(key, value);
            }
        }
        return queryString;
    }

    onChange(e, { name, value }) {
        const query = this.state.query;

        if (value === "" || value === null) {
            delete query[name];
        } else {
            query[name] = value;
        }

        this.setState({ query }, async () => {
            const params = this.getUrlSearchParams();
            console.log(params.toString());
            const newPathQuery = `${window.location.pathname}?${params.toString()}`;
            window.history.pushState(null, '', newPathQuery);
            await this.onAccountSearch();
        });
    }

    onClearValue(e, { name, value }) {
        const query = this.state.query;
        query[name] = "";
        this.setState({ query }, this.onChange(e, {}));
    }

    async onAccountSearch(e) {
        if (e) {
            e.preventDefault();
        }
        this.setState({loading:true});

        let results = [];

        if (this.state.query.searchString && this.state.query.searchString.length > 0) {
            const encodedSearchString = encodeURIComponent(this.state.query.searchString);
            try {

                const adminApiQuery = async (url) => {
                    try {
                        return await superagent.get(url).accept("json");
                    } catch (e) {
                        return null;
                    }
                }

                const res = await Promise.all([
                    adminApiQuery(`/api/admin/account/query/email/${encodedSearchString}`),
                    adminApiQuery(`/api/admin/account/query/username/${encodedSearchString}`),
                    adminApiQuery(`/api/admin/account/query/oculusId/${encodedSearchString}`),
                    adminApiQuery(`/api/admin/search/ip/${encodedSearchString}`),
                    adminApiQuery(`/api/admin/search/device/${encodedSearchString}`)
                ]);

                results = res.filter(r => r && r.body != null).map(r => r.body);
                results = _.flatten(results);
                results = results.filter(r => r != null);
            } catch (e) {
                console.log(e);
            }
        }
        this.setState({loading:false, results});
    }

    render() {
        const results = (this.state.results && this.state.results.length == 0) ? (
            <Segment basic>
                <Header as="h4">
                Nothing found.
                </Header>
            </Segment>
        ) : (<div>
                <Header as="h4">
                Found {this.state.results.length} results.
                </Header>
                {this.state.results.map(account => 
                    <Segment>
                        <Header as="h4" image>
                            <Image src="/images/avatar_b.jpg" rounded size="mini" />
                            <Header.Content>
                            <a href={`/account/${account.id}`}>{account.username}</a>
                            <Header.Subheader>Account Id: {account.id}</Header.Subheader>
                            </Header.Content>
                        </Header>
                    </Segment>
                )}
            </div>
        );

        return (
            <div>
                <AccountsWrapper title="Account Search" menuItems={[]} loading={this.state.loading}>
                    <Header as="h3">
                        <Header.Content>Search by username, email address, ip address or device id
                        </Header.Content>
                    </Header>
                    <Segment secondary>
                        <Form size="huge" onSubmit={this.onAccountSearch.bind(this)}>
                            <Form.Group widths="equal">
                                <Form.Input 
                                    icon="user" label="" placeholder="email or username" 
                                    value={this.state.query.searchString}
                                    name="searchString" onChange={this.onChange.bind(this)} focus />
                                <Button size="huge" icon="right arrow" labelPosition="right" content="Search" type="submit" />
                            </Form.Group>
                        </Form>
                    </Segment>

                    <AccountSearchResultsTable results={this.state.results} />

                </AccountsWrapper>
            </div>
        );
    }
}

export default AccountSearch;
