<commit_before>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react';
import PropTypes from 'prop-types';
import {Button, Dropdown, Grid, Icon, Image, List, Message, Segment} from 'semantic-ui-react';
import getLocationsURL from 'indico-url:rooms_new.locations';
import {indicoAxios, handleAxiosError} from 'indico/utils/axios';
import {Translate} from 'indico/react/i18n';

import './RoomSelector.module.scss';


const fetchLocations = async () => {
    let response;
    try {
        response = await indicoAxios.get(getLocationsURL());
    } catch (error) {
        handleAxiosError(error);
        return;
    }

    return response;
};


export default class RoomSelector extends React.Component {
    static propTypes = {
        onChange: PropTypes.func.isRequired,
        initialValue: PropTypes.array
    };

    static defaultProps = {
        initialValue: []
    };

    constructor(props) {
        super(props);
        const {initialValue, onChange} = this.props;

        if (initialValue) {
            onChange(initialValue);
        }

        this.state = {
            isFetchingLocations: false,
            locations: [],
            selectedLocation: null,
            selectedRoom: null,
            selectedRooms: initialValue
        };
    }

    removeItem = (room) => {
        const {selectedRooms} = this.state;
        const {onChange} = this.props;
        const newRooms = selectedRooms.filter((selectedRoom) => selectedRoom.id !== room.id);

        this.setState({selectedRooms: newRooms}, () => {
            onChange(newRooms);
        });
    };

    renderRoomItem = (room) => {
        return (
            <List.Item key={room.id}>
                <Image src={room.large_photo_url} size="mini" />
                <List.Content>
                    <List.Header>{room.full_name}</List.Header>
                </List.Content>
                <List.Content styleName="remove-btn-content">
                    <Icon name="remove"
                          onClick={() => this.removeItem(room)} />
                </List.Content>
            </List.Item>
        );
    };

    render() {
        const {onChange} = this.props;
        const {locations, selectedLocation, selectedRoom, selectedRooms: rooms, isFetchingLocations} = this.state;
        const locationOptions = locations
            .sort((a, b) => a.name.localeCompare(b.name))
            .map((location) => {
                return {text: location.name, value: location.id};
            });
        let roomOptions = [];
        if (selectedLocation) {
            roomOptions = selectedLocation.rooms
                .filter((room) => rooms.findIndex((item) => item.id === room.id) === -1)
                .sort((a, b) => a.full_name.localeCompare(b.full_name))
                .map((room) => {
                    return {text: room.full_name, value: room.id};
                });
        }

        return (
            <Grid styleName="room-selector">
                <Grid.Row>
                    <Grid.Column width={5}>
                        <Dropdown placeholder={Translate.string('Location')}
                                  options={locationOptions}
                                  value={selectedLocation && selectedLocation.id}
                                  loading={isFetchingLocations}
                                  onChange={(event, data) => {
                                      const selected = locations.find((loc) => loc.id === data.value);
                                      this.setState({selectedLocation: selected});
                                  }}
                                  onOpen={() => {
                                      if (locations.length) {
                                          return;
                                      }

                                      this.setState({isFetchingLocations: true}, async () => {
                                          const result = await fetchLocations();
                                          this.setState({locations: result.data, isFetchingLocations: false});
                                      });
                                  }}<commit_msg>Fetch room locations after component mounted<commit_after>/* This file is part of Indico.
 * Copyright (C) 2002 - 2018 European Organization for Nuclear Research (CERN).
 *
 * Indico is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Indico is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Indico; if not, see <http://www.gnu.org/licenses/>.
 */

import React from 'react';
import PropTypes from 'prop-types';
import {Button, Dropdown, Grid, Icon, Image, List, Message, Segment} from 'semantic-ui-react';
import getLocationsURL from 'indico-url:rooms_new.locations';
import {indicoAxios, handleAxiosError} from 'indico/utils/axios';
import {Translate} from 'indico/react/i18n';

import './RoomSelector.module.scss';


const fetchLocations = async () => {
    let response;
    try {
        response = await indicoAxios.get(getLocationsURL());
    } catch (error) {
        handleAxiosError(error);
        return;
    }

    return response;
};


export default class RoomSelector extends React.Component {
    static propTypes = {
        onChange: PropTypes.func.isRequired,
        initialValue: PropTypes.array
    };

    static defaultProps = {
        initialValue: []
    };

    constructor(props) {
        super(props);
        const {initialValue, onChange} = this.props;

        if (initialValue) {
            onChange(initialValue);
        }

        this.state = {
            isFetchingLocations: false,
            locations: [],
            selectedLocation: null,
            selectedRoom: null,
            selectedRooms: initialValue
        };
    }

    componentDidMount() {
        // eslint-disable-next-line react/no-did-mount-set-state
        this.setState({isFetchingLocations: true}, async () => {
            const result = await fetchLocations();
            this.setState({locations: result.data, isFetchingLocations: false});
        });
    }

    removeItem = (room) => {
        const {selectedRooms} = this.state;
        const {onChange} = this.props;
        const newRooms = selectedRooms.filter((selectedRoom) => selectedRoom.id !== room.id);

        this.setState({selectedRooms: newRooms}, () => {
            onChange(newRooms);
        });
    };

    renderRoomItem = (room) => {
        return (
            <List.Item key={room.id}>
                <Image src={room.large_photo_url} size="mini" />
                <List.Content>
                    <List.Header>{room.full_name}</List.Header>
                </List.Content>
                <List.Content styleName="remove-btn-content">
                    <Icon name="remove"
                          onClick={() => this.removeItem(room)} />
                </List.Content>
            </List.Item>
        );
    };

    render() {
        const {onChange} = this.props;
        const {locations, selectedLocation, selectedRoom, selectedRooms: rooms, isFetchingLocations} = this.state;
        const locationOptions = locations
            .sort((a, b) => a.name.localeCompare(b.name))
            .map((location) => {
                return {text: location.name, value: location.id};
            });
        let roomOptions = [];
        if (selectedLocation) {
            roomOptions = selectedLocation.rooms
                .filter((room) => rooms.findIndex((item) => item.id === room.id) === -1)
                .sort((a, b) => a.full_name.localeCompare(b.full_name))
                .map((room) => {
                    return {text: room.full_name, value: room.id};
                });
        }

        return (
            <Grid styleName="room-selector">
                <Grid.Row>
                    <Grid.Column width={5}>
                        <Dropdown placeholder={Translate.string('Location')}
                                  options={locationOptions}
                                  value={selectedLocation && selectedLocation.id}
                                  loading={isFetchingLocations}
                                  onChange={(event, data) => {
                                      const selected = locations.find((loc) => loc.id === data.value);
                                      this.setState({selectedLocation: selected});
                                  }}
{'fraction_non_alphanumeric': 0.11125039172673143, 'fraction_numerical': 0.0027159720045962605, 'mean_word_length': 1.7464142283419393, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 62, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 27, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4553094', 'n_tokens_mistral': 2472, 'n_tokens_neox': 2397, 'n_words': 626}