/*
 * Copyright (C) 2019. Jay Chang
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
    colors,
    FlipperPlugin,
    Heading,
    styled,
} from "flipper";
import React from "react";

interface InfoRow {
    title: string;
    value: string;
}

interface InfoGroup {
    title: string;
    rows: InfoRow[];
}

interface PersistedState {
    groups: InfoGroup[];
}

const Container = styled("div")({
    margin: 10,
});

const Row = styled("tr")({
    ":hover": { backgroundColor: colors.highlightBackground },
});

const Column = styled("td")({
    borderStyle: "solid",
    borderWidth: 1,
    padding: 8,
});

export default class InfoPlugin extends FlipperPlugin<any, any, PersistedState> {
    public static defaultPersistedState = {
        groups: [],
    };

    public init() {
        this.client.call("getInfoGroups")
            .then((groups: InfoGroup[]) => {
                this.props.setPersistedState({ groups });
            });
    }

    public render() {
        const { groups } = this.props.persistedState;
        const rowProvider = (row: InfoRow, index: number) => {
            return (
                <Row key={index}>
                    <Column>{row.title}</Column>
                    <Column>{row.value}</Column>
                </Row>
            );
        };
        const groupViews = groups.map((group, index) => {
            const rows = group.rows.map(rowProvider);
            return (
                <Container key={index}>
                    <Heading>{group.title}</Heading>
                    <table>{rows}</table>
                </Container>
            );
        });
        return groupViews;
    }
}
