import * as React from 'react';
import { RouteComponentProps } from 'react-router';
import AssetConfigurator from './asset-configurator';
import { AssetConfiguration, getAssetConfigurationFromQueryString } from '../asset-configuration';
import '../../css/asset-configuration.css';

export default class AssetConfigurationPage extends React.Component<RouteComponentProps, AssetConfiguration> {
    constructor(props: RouteComponentProps) {
        super(props);
        this.state = {} as AssetConfiguration;
    }

    public componentDidMount() {
        const assetConfiguration = getAssetConfigurationFromQueryString(this.props.location.search);
        this.setState(assetConfiguration);
    }

    public render() {
        return (
            <div className="asset-configuration">
                <h1 style={{ textAlign: 'center' }}>Asset Configuration</h1>
                <AssetConfigurator
                    deviceId={this.state.deviceId}
                    drmType={this.state.drmType}
                    licensingUri={this.state.licensingUri}
                    manifestUri={this.state.manifestUri}
                    streamType={this.state.streamType}
                    onUpdateManifestUri={this.handleUpdateManifestUri}
                    onUpdateLicensingUri={this.handleUpdateLicensingUri}
                    onUpdateDeviceId={this.handleUpdateDeviceId}
                    onUpdateDRMType={this.handleUpdateDRMType}
                    onUpdateStreamType={this.handleUpdateStreamType}
                    onLoadPlayer={() => this.onPlayButtonClick()}
                />
            </div>
        );
    }

    private handleUpdateDeviceId = (deviceId: string) => {
        this.setState({ deviceId });
    };

    private handleUpdateDRMType = (drmType: string) => {
        this.setState({ drmType });
    };

    private handleUpdateLicensingUri = (licensingUri: string) => {
        this.setState({ licensingUri });
    };

    private handleUpdateManifestUri = (manifestUri: string) => {
        this.setState({ manifestUri });
    };

    private handleUpdateStreamType = (streamType: string) => {
        this.setState({ streamType });
    };

    private buildSearchString(): string {
        let search = `?manifestUri=${encodeURIComponent(this.state.manifestUri)}`;
        if (this.state.licensingUri) {
            search += `&licensingUri=${encodeURIComponent(this.state.licensingUri)}`;
        }
        if (this.state.deviceId) {
            search += `&deviceId=${encodeURIComponent(this.state.deviceId)}`;
        }
        if (this.state.drmType) {
            search += `&drmType=${encodeURIComponent(this.state.drmType)}`;
        }
        if (this.state.streamType) {
            search += `&streamType=${encodeURIComponent(this.state.streamType)}`;
        }
        return search;
    }

    private onPlayButtonClick(): void {
        const search = this.buildSearchString();
        this.props.history.push(`/player${search}`);
    }
}
