import * as React from 'react'
import { ColumnProps } from 'antd/lib/table';
import { Table } from 'antd';
import { compose, DataValue } from 'react-apollo';
import { withPlatforms } from '../graphql';
import { platforms, platforms_platforms, platforms_platforms_icon } from '../graphql/types/platforms';
import { getScript_script_platform } from '../graphql/types/getScript';
import AssetIcon from './AssetIcon';


interface PlatformRowItem {
    os: string
    dist: string
    icon: platforms_platforms_icon
    codename: string
}

const COLUMNS: ColumnProps<any>[] = [
    {
        title: "",
        dataIndex: "icon",
        key: "icon",
        width: "32px",
        render: ({ id }) => <AssetIcon size={32} id={id} />
    },
    {
        width: "33%",
        title: "Operation System",
        dataIndex: "os",
        key: "os"
    },
    {
        width: "33%",
        title: "Distribution",
        dataIndex: "dist",
        key: "dist"
    },
    {
        width: "33%",
        title: "Codename",
        dataIndex: "codename",
        key: "codename",
        align: "right"
    },
];


interface ChildData {
    support: getScript_script_platform[]
    platforms: DataValue<platforms, {}>
}

interface Props {

}

class PlatformTable extends React.Component<Props & ChildData> {
    render() {
        const { platforms } = this.props;

        // @todo: optimize
        const items = this.constructItems(platforms.platforms || []);

        return (
            <Table pagination={false} columns={COLUMNS} dataSource={items} />
        )
    }

    private constructItems(platforms: platforms_platforms[]): PlatformRowItem[] {
        const { support } = this.props;
        const items: PlatformRowItem[] = [];
        const index: { [k: string]: PlatformRowItem } = {};

        platforms.forEach((platform) => {
            platform.releases.forEach((release) => {
                const item = {
                    codename: release.codename,
                    dist: platform.dist,
                    icon: platform.icon,
                    os: platform.os
                };
                index[`${item.os}:${item.dist}:${item.codename}`] = item;
                items.push(item);
            });
        });

        return support.map(item => {
            const key = `${item.os}:${item.dist}:${item.codename}`;
            if (index[key]) {
                return index[key];
            } else {
                return { ...item, icon: null };
            }
        });
    }
}

export default compose(
    withPlatforms
)(PlatformTable);
