import * as vscode from 'vscode';

export class TextDocumentContentProvider implements vscode.TextDocumentContentProvider {
    private _onDidChange = new vscode.EventEmitter<vscode.Uri>();
    private _data = null;

    public provideTextDocumentContent(uri: vscode.Uri): string {
        if (!this._data) return this.errorSnippet();
        
        let styles = `<style>
                    table {
                        border: solid 1px white;
                        border-collapse: collapse;
                    }
                    table td, table th {
                        border: solid 1px white;
                        padding: 3px;
                    }
                </style>`

        let text = `<body>${styles}<table><tr>`
        text += this._data['columnDefinitions'].map((x) => `<th>${x['name']}</th>`).join('')
        text += '</tr>'
        text += this._data['rows'].map((r) => 
            '<tr>' + r['columns'].map((c) => '<td>' + c['value'] + '</td>').join('') + '</tr>'
        ).join('')
        text += '</table></body>'
        return text;
    }

    get onDidChange(): vscode.Event<vscode.Uri> {
        return this._onDidChange.event;
    }

    public update(uri: vscode.Uri) {
        this._onDidChange.fire(uri);
    }

    public setData(data) {
        this._data = data;
    }

    private errorSnippet(): string {
        return `
            <body>
                <table>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                    </tr>
                    <tr>
                        <td>1</td>
                        <td>Foobar</td>
                    </tr>
                </table>
            </body>`;
    }
}