import { Component, h, Event, EventEmitter, State, Prop, Element, Watch } from '@stencil/core'
import { stringContainsJson } from '../../shared/utils'
import { HistoryItem } from '../gd-user-dashboard-list-item/user-dashboard-list-item'

@Component({
    tag: 'gd-user-dashboard-import-dialog',
    styleUrl: 'gd-user-dashboard-import-dialog.scss',
    shadow: true,
})
export class GdUserDashboardImportDialog {
    
    /**
     * when to show the dialog
     */
    @Prop() show: boolean = false

    /**
     * event emitted when the dialog is closed
     */
    @Event() closed: EventEmitter<void>

    /**
     * event emitted to import items
     */
    @Event() import: EventEmitter<Array<HistoryItem>>

    /**
     * the imported history items
     */
    @State() historyItems: Array<HistoryItem> = []

    /**
     * a visual state to show loading in the import button
     */
    @State() importing: boolean = false

    /**
     * an error to show when the import is invalid or otherwise fails
     */
    @State() invalidError: string

    @Element() el: HTMLElement

    @Watch('show')
    setImportOptions() {
        if (this.show) {
            this.historyItems = []
        }
    }

    handleChange(event) {
        if (event?.detail?.length <= 0) {
            return
        }

        const file = event.detail[0]
        const reader = new FileReader()

        reader.addEventListener('load', (event) => {
            const result: any = event.target.result

            if (stringContainsJson(result)) {
                this.historyItems = [].concat(JSON.parse(result))
            } else {
                this.invalidError = 'The file you uploaded contains invalid JSON'
            }
        })
        
        reader.readAsText(file)
    }

    handleClose() {
        if (this.importing) return
        this.invalidError = null
        this.el.shadowRoot.querySelector('bs-modal').closeDialog()
    }

    importItems() {
        if (!this.historyItems.length) return
        
        this.invalidError = null
        this.importing = true

        this.import.emit(this.historyItems)

        // visually wait a bit before closing
        setTimeout(() => {
            this.importing = false
            this.handleClose()
        }, 1000)
    }

    /**
     * renders the dialog
     */
    render() {
        return (
            <bs-modal show={this.show} onClose={() => this.closed.emit()}>
                <bs-modal-header modal-title={`<bs-icon size="20" class="mr-2" icon="fab fa-file-import"></bs-icon> Import`} />

                <bs-modal-body>                    
                    <bs-form-row>
                        <bs-form-group>
                            <bs-form-file accept=".json" file-id="fileUpload" label="Choose a file to import" onBsInput={this.handleChange.bind(this)} />
                        </bs-form-group>
                    </bs-form-row>
                </bs-modal-body>

                <bs-modal-footer>
                    <bs-button variant="secondary" onClick={this.handleClose.bind(this)} disabled={this.importing}>
                        Cancel
                    </bs-button>

                    {this.importing ? (
                        <bs-button variant="primary" disabled>
                            <bs-spinner aria-hidden="true" size="sm"></bs-spinner>
                            <span class="ml-2">Importing...</span>
                        </bs-button>
                    ) : (
                        <bs-button variant="primary" onClick={this.importItems.bind(this)} disabled={!this.historyItems.length}>
                            Import
                        </bs-button>
                    )}
                </bs-modal-footer>
            </bs-modal>
        )
    }
}
