text:
<repo_name>newkater/roomie<file_sep>/src/components/poll-list/index.js
import PollList from "./poll-list";

export default PollList;<file_sep>/src/components/profile-block/index.js
import ProfileBlock from './profile-block';

export default ProfileBlock;<file_sep>/src/components/group-blocks/group-blocks.js
import React, {Fragment} from 'react';
import {Column} from "bloomer";

import GroupBlock from '../group-block';

const GroupBlocks = ({groups, type, groupUpdate, adStyle, apply, cancel}) => {
    //console.log(groups);
    const groupsList = groups.map((el) => {
        //console.log("group-blocks", el);
        return (
            <Column isSize={'1/3'} >
                <GroupBlock key={el.id} cancel={cancel} apply={apply} type={type} group={el} groupUpdate={groupUpdate} adStyle={adStyle}/>
            </Column>
        );
    });
    return (
        <Fragment>
            {groupsList}
        </Fragment>
    );
};

export default GroupBlocks;<file_sep>/src/components/register-form/register-form.js
import React, {Component} from "react";
import debounce from "lodash";
import "./register-form.css";
import {Button, Control, Field, Input, Label} from "bloomer";
import {COUNTRIES} from "../../utils/countries";
import Select from 'react-select';
import {withRouter} from 'react-router-dom';
import "react-date-picker/dist/DatePicker.css";
import Data from "../../data";

const dalshe = {
    "background": "#001AFF",
    "border-radius": "4px",
    "font-family": "Roboto",
    "font-weight": "500",
    "font-size": "14px",
    "line-height": "16px",
    "letter-spacing": "0.25px",

    "color": "#FFFFFF"
};

const genders = [
    { value: 'MALE', label: 'Мужской' },
    { value: 'FEMALE', label: 'Женский' }
];

const habits = [
    {value: "Нет", label: "Нет"},
    {value: "Курение", label: "Курение"},
    {value: "Алкоголь", label: "Алкоголь"},
    {value: "Курение и алкоголь", label: "Курение и алкоголь"}
];

const timePeriods = [
    { value: 1, label: '1 месяц' },
    { value: 3, label: 'до 3 месяцев' },
    { value: 6, label: 'до 6 месяцев' },
    { value: 9, label: 'до 9 месяцев' },
    { value: 12, label: 'больше' }
];

const roommatesNumber = [
    {value: 1, label: '1'},
    {value: 2, label: '2'},
    {value: 3, label: '3'},
    {value: 4, label: '4'},
    {value: 5, label: '5'},
    {value: 6, label: '6'}
];

let putError = (password, pass) => {
    return ((password !== pass) || (pass === '' && password === ''));
};

let debouncedError = (password, pass) => {
    //console.log("debouncedError came ", putError(password, pass));
    return (debounce(putError(password, pass), 500));
};

class RegisterForm extends Component {
    data= new Data();
    state = {
        email: '',
        password: '',
        pass: '',
        userName: '',
        sex: '',
        birthCountry: '',
        birthCity: '',
        birthDate: '',
        university: '',
        speciality: '',
        phoneNumber: '',
        currentCity: 183,
        maxRoommatesNumber: '',
        rentalPeriod: '',
        languages: null,
        badHabits: '',
        userInfo: '',
        isPasswordCorrect: true,
        cities: [],
        specialities: [],
        universities: []
    };

    getCities = (countryName) => {
        this.data.getCities({countryName}).then(res => {
            console.log("getCities", res);
            return res;
        }).then(res => this.setState({cities: res})).then(() => console.log("handle cities1", this.state.cities));
    };

    getUniversities = (cityId) => {
        this.data.getUniversities({cityId}).then(res => {
            console.log("getUniversities", res);
            return res;
        }).then(res => this.setState({universities: res})).then(() => console.log("handle universities", this.state.universities));
    };

    getSpecialities = (universityId) => {
        this.data.getSpecialities({universityId})
        // .then(res => {
        //     console.log("getSpecialities", res);
        //     return res;
        // })
            .then(res => this.setState({specialities: res}))
        // .then(() => console.log("after", this.state.specialities));
    };

    handleInput = (key, value) => {
        if (key === 'pass') {
            debouncedError();
            console.log(debouncedError());
        }
        this.setState({[key]: value} );
        console.log(this.state);
    };

    handleSubmit = (event) => {
        const {register, history} = this.props;
        console.log("register props", this.props);
        event.preventDefault();
        console.log("Submit", this.state);
        let lang = [...this.state.languages];
        lang= lang.map((item) => {return {id: item.id}});
        register(
            {
                email: this.state.email,
                password: <PASSWORD>,
                userName: this.state.userName,
                sex: this.state.sex.value,
                birthCountry: this.state.birthCountry.value,
                birthDate: this.state.birthDate,
                birthCity: this.state.birthCity.value,
                university: this.state.university.value,
                speciality: this.state.speciality.value,
                phoneNumber: this.state.phoneNumber,
                currentCity: this.state.currentCity.value,
                maxRoommatesNumber: this.state.maxRoommatesNumber.value,
                rentalPeriod: this.state.rentalPeriod.value,
                languages: lang,
                badHabits: this.state.badHabits.value,
                userInfo: this.state.userInfo
            });
        history.push('/');
    };

    handleChangeCountry = (value) => {
        this.setState({birthCountry: value} );
        this.getCities(value.value);
        console.log("value", value);
        console.log("handle cities", this.state.cities);
    }

    handleChangeCity = (value) => {
        this.setState({currentCity: value} );
        this.getUniversities(value.value);
        console.log("value", value);
        console.log("handle universities", this.state.universities);
    }

    handleChangeUniversity = (value) => {
        this.setState({university: value} );
        this.getSpecialities(value.value);
        //console.log("value", value);
        //console.log("handle cities", this.state.cities);
    }

    render() {
        const { page, changePage, almatyUniversities, kazakhCities } = this.props;

        const allLanguages=this.props.languages;

        const {specialities, cities, universities} = this.state;

        if (page === 3) {
            return (
                <form>
                    <Field>
                        Максимальное число сожителей
                        <Control>
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleInput('maxRoommatesNumber', value)}
                                    options={roommatesNumber}
                                    className="is-fullwidth mandatory-field"
                                    value={this.state.maxRoommatesNumber}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Период аренды
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleInput('rentalPeriod', value)}
                                    options={timePeriods}
                                    className="is-fullwidth mandatory-field"
                                    value={this.state.rentalPeriod}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Языки
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isMulti
                                    options={allLanguages}
                                    isSearchable
                                    closeMenuOnSelect={false}
                                    onChange={(value) => this.handleInput('languages', value)}
                                    className="is-fullwidth mandatory-field"
                                    value={this.state.languages}
                                />
                        </Control>
                    </Field>
                    <Field>
                        В каком городе вы ищете жилье?
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleChangeCity(value)}
                                    options={kazakhCities}
                                    className="is-fullwidth mandatory-field"
                                    value={this.state.currentCity}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Университет или колледж
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleChangeUniversity(value)}
                                    options={universities}
                                    className="is-fullwidth"
                                    value={this.state.university}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Специальность
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleInput('speciality', value)}
                                    options={specialities}
                                    className="is-fullwidth"
                                    value={this.state.speciality}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Есть ли вредные привычки
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleInput('badHabits', value)}
                                    options={habits}
                                    className="is-fullwidth"
                                    value={this.state.badHabits}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Дополнительная информация
                        <Control>
                            <textarea  style={{"width": "100%"}}
                                       className="textarea"
                                       onChange={(event) => this.handleInput('userInfo', event.target.value)}
                                       placeholder=''
                                       isSize="medium"/>
                        </Control>
                    </Field>

                        { page === 3 && <Button disabled={this.state.maxRoommatesNumber==="" || this.state.languages===null || this.state.currentCity==="" || this.state.rentalPeriod===""} type="submit" onClick={this.handleSubmit} isColor='info' style={{"width": "100%", "height": "54px"}}>Готово!</Button> }

                </form>
            )
        }

        if (page === 2) {
            return (
                <form>
                    <Field>
                        ФИО
                        <Control>
                            <Input type="text"
                                   className="mandatory-field"
                                   onChange={(event) => this.handleInput('userName', event.target.value)}
                                   placeholder='<NAME>'
                                   isSize="medium"
                                   value={this.state.userName}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Дата рождения
                        <Control>
                            <Input type="date"
                                   className="mandatory-field"
                                   isSize="medium"
                                   value={this.state.birthDate}
                                   onChange={(event) => this.handleInput('birthDate', event.target.value)}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Пол
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    options={genders}
                                    onChange={(value) => this.handleInput('sex', value)}
                                    className="is-fullwidth mandatory-field"
                                    value={this.state.sex}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Родная страна
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleChangeCountry(value)}
                                    options={COUNTRIES}
                                    className="is-fullwidth mandatory-field"
                                    value={this.state.birthCountry}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Родной город
                        <Control className="is-expanded">
                            <Select isSize="medium"
                                    isSearchable
                                    closeMenuOnSelect={true}
                                    onChange={(value) => this.handleInput('birthCity', value)}
                                    options={kazakhCities}
                                    className="is-fullwidth"
                                    value={this.state.birthCity}
                            />
                        </Control>
                    </Field>
                    <Field>
                        Контактный телефон
                        <Control>
                            <Input type="tel"
                                   onChange={(event) => this.handleInput('phoneNumber', event.target.value)}
                                   isSize="medium"
                                   placeholder=''/>
                        </Control>
                    </Field>

                        <Button disabled={this.state.userName==="" || this.state.birthDate==="" || this.state.birthCountry===""} onClick={() => changePage(page + 1)} isSize='large' isColor='info' style={{dalshe}}>Дальше</Button>

                </form>
            )
        }

        return (
            <form>
                <Field>
                    Электронная почта
                    <Control>
                        <Input type="email"
                               className="mandatory-field"
                               onChange={(event) => this.handleInput('email', event.target.value)}
                               placeholder='<EMAIL>'
                               isSize="medium"/>
                    </Control>
                </Field>
                <Field>
                    Пароль
                    <Control>
                        <Input type="password"
                               className="mandatory-field"
                               onChange={(event) => this.handleInput('password', event.target.value)}
                               isSize="medium"
                               placeholder='password'/>
                    </Control>
                </Field>
                <Field>
                    Повторите пароль
                    <Control>
                        <Input type="password"
                               className="mandatory-field"
                               isSize="medium"
                               onChange={(event) => this.handleInput('pass', event.target.value)}
                               placeholder='password'/>
                    </Control>

                        {
                            (putError(this.state.password, this.state.pass) && this.state.pass !== '' && this.state.password !== '') &&

Неверный пароль

                        }

                </Field>

                    <Button disabled={putError(this.state.password, this.state.pass) || this.state.email===""} onClick={(() => changePage(page + 1))} isSize='large' isColor='info' style={{dalshe}}>Дальше</Button>

            </form>
        )
    }
}

export default withRouter(RegisterForm);<file_sep>/src/pages/group.js
import React, {Component, Fragment} from 'react';
import {Container} from "bloomer";
import GroupBlock from "../components/group-block";
import UsersListCollapse from "../components/users-list-collapse";
import "./group.css";
import PollList from "../components/poll-list";
import {Link} from "react-router-dom";
import LinksBlock from "../components/links-block/links-block";
import Data from './../data';

class GroupPage extends Component {
    data = new Data();

    state = {
        groupBlockType: "2",
        group: this.props.group || null,
        loading: false,
        error: false
    };

    isClick = () => {
        this.setState({groupBlockType: "3"});
    };

    isMember = () => {
        if (!this.state.group) {
            return false;
        }
        return this.state.group.members.findIndex(x => x.id==sessionStorage.getItem('id')) > -1;
    };

    isApplicant = () => {
        return this.state.group.applications.findIndex(x => x.id==sessionStorage.getItem('id')) > -1;
    }

    componentDidMount() {
        window.scrollTo(0, 0);
        if (!this.state.group) {
            this.setState({loading: true, error: false});
            this.data.getGroup(this.props.id).then((group) => {this.setState({loading: false, group: group, error: false})})
                .catch((err) => this.setState({error: true, loading:false, group: null}))
        }

    }

    render() {

        const elements = [
            {
                id: 1,
                type: "DELETE",
                person: "person1",
                positive: 3,
                negative: 2
            }, {
                id: 2,
                type: "ADD",
                person: "person2",
                positive: 3,
                negative: 7
            }, {
                id: 3,
                type: "DELETE",
                person: "person3",
                positive: 3,
                negative: 4
            }
            ];
        const {groupBlockType, group, error, loading} = this.state;
        let {groupUpdate, apply, cancel} = this.props;
        //console.log("group page props ", this.props);
        console.log("group page", group);
        const {name, members, applications, telegramLink, whatsappLink} = group;
        console.log("name group", name);
        console.log("check", this.isMember());
        const arr = applications.map((item) => {return {
            id: item.id,
            type: "ADD",
            person: item.name,
            positive: 0,
            negative: 0
        }});

        return (
            <Container>
                {loading &&
Loading group
}
                {error &&
Группа не найдена
}
                { group &&
                <Fragment>
                    <Link to="/">

Назад к списку групп

                    </Link>

{name}

                                <GroupBlock type={groupBlockType}
                                            apply={apply}
                                            cancel={cancel}
                                            isClick={this.isClick}
                                            groupUpdate={groupUpdate}
                                            group={group}
                                            showMembers={false}
                                            showHeader={false}
                                />

                            {
                                this.isMember() &&

                                    <LinksBlock telegramLink={telegramLink} whatsappLink={whatsappLink}/>

                            }

                            <UsersListCollapse name="Участники" membersNumber={members.length} usersList={members}/>
                            <UsersListCollapse name="Заявки на участие" membersNumber={applications.length} usersList={applications}/>
                            <PollList name="Опросы" membersNumber={arr.length} pollList={arr} groupUpdate={groupUpdate} group={group}/>

                    {/*<Columns>*/}
                    {/*    <Column isSize="1/3">*/}
                    {/*        <GroupBlock type={groupBlockType} isClick={this.isClick} group={group}/>*/}
                    {/*    </Column>*/}
                    {/*    <Column>*/}
                    {/*        <UsersListCollapse name="Участники" membersNumber={group.members.length} usersList={group.members}/>*/}
                    {/*        <UsersListCollapse name="Заявки на участие" membersNumber={group.applications.length} usersList={group.applications}/>*/}
                    {/*    </Column>*/}
                    {/*</Columns>*/}
                </Fragment>
                }
            </Container>
        );
    }
}

export default GroupPage;<file_sep>/src/components/users-list-item/index.js
import UsersListItem from "./users-list-item"

export default UsersListItem;<file_sep>/src/components/group-block/group-block.js
import React, {Component} from 'react'
import {Box, Button} from "bloomer";
import {Link} from 'react-router-dom';
import "./group-block.css";
import Avatar from "../avatar";
import camera from './../../images/camera-black.svg';

const boxStyle = {
    background: "#FFFFFF",
    boxShadow: "0px 0px 48px rgba(0, 0, 0, 0.05)",
    borderRadius: "8px",
    width: "352px",
    padding: "36px 24px"
};

const boxStyle1 = {
    background: "#FFFFFF",
    boxShadow: "0px 0px 48px rgba(0, 0, 0, 0.05)",
    borderRadius: "8px",
    width: "352px",
    height: "450px",
    padding: "36px 24px"
};

const buttonStyle = {
    fontFamily: "Roboto",
    fontStyle: "normal",
    fontWeight: 500,
    fontSize: "18px",
    color: "#0019FF"
}

const buttonStyle1 = {
    display: "flex",
    background: "#001AFF",
    borderRadius: "4px",
    fontFamily: "Roboto",
    fontWeight: "500",
    fontSize: "14px",
    lineHeight: "16px",
    textAlign: "center",
    letterSpacing: "0.25px",
    width: "90%",
    height: "50px",

    color: "#FFFFFF"
}

const buttonStyle2 = {
    fontFamily: "Roboto",
    fontWeight: "500",
    fontSize: "18px",
    lineHeight: "21px",
    textalign: "center",
    letterSpacing: "0.25px",

    color: "#C2C2C2"
}

const plus = (num) => {
    return(

            +{num}

    )
}

const membersList = (members) => {
    if (members==undefined) return;
    const firstMembers = members.slice(0, 3);
    return(

            {firstMembers.map(member => <Avatar size={64} image={member.photo || camera}/>)}
            {(members.length === 4) && <Avatar size={64} image={members[3].photo || camera}/>}
            {(members.length > 4) && plus(members.length - 3)}

    )
};

const infoItem = (title, value) => {
    return (

                {title}

                {value}

    )
};

export default class GroupBlock extends Component {

    state = {
        groupBlockType: this.props.type,
        id: this.props.group.id,
        name: this.props.group.name,
        city: this.props.group.city,
        groupInfo: this.props.group.groupInfo,
        memberNumber: this.props.group.memberNumber,
        peopleNumber: this.props.group.peopleNumber,
        rentalPeriod: this.props.group.rentalPeriod,
        free: this.props.group.free,
        members: this.props.group.members,
        applications: this.props.group.applications,
        polls: this.props.group.polls
    };

    isMember = () => {
        let {members} = this.state;
        if (members == undefined || members==null) members = [];
        const id = sessionStorage.getItem('id');
        let arr = ((members == undefined || members==null)?[]:members.filter((item) => {return item.id==id}));
        //console.log("member", arr.length!==0, typeof id, members);
        return arr.length!==0;
    };

    isApplicant = () => {
        let {applications} = this.state;
        //console.log("applicant", applications);
        if (applications == undefined || applications==null) applications = [];
        const id = sessionStorage.getItem('id');
        let arr = ((applications == undefined || applications==null)?[]:applications.filter((item) => {return item.id==id}))
        //console.log("applicant", arr.length!==0, applications);
        return arr.length!==0;
    };

    addApplication = () => {
        const groupId = this.props.group.id;
        const user = {
            id: sessionStorage.getItem('id'),
            name: sessionStorage.getItem('name'),
            age: undefined,
            photo: sessionStorage.getItem('photo'),
            userCity: undefined,
            userInfo: undefined
        }
        this.props.apply({user, groupId});
        this.setState({groupBlockType: "3"});
        this.setState({applications: [...this.state.applications, {
                id: sessionStorage.getItem('id'),
                name: sessionStorage.getItem('name'),
                age: undefined,
                photo: sessionStorage.getItem('photo'),
                userCity: undefined,
                userInfo: undefined
            }]});
        this.handleSubmit();
    };

    deleteApplication = () => {
        const groupId = this.props.group.id;
        const userId = sessionStorage.getItem('id');
        this.props.cancel({groupId, userId});

        this.setState({groupBlockType: "1"});
        let array = [...this.state.applications];
        const index = Number(sessionStorage.getItem('id'));
        array.splice(index, 1);
        this.setState({applications: this.state.applications.filter(u => u.id != userId)});
        this.handleSubmit();
        //this.forceUpdate();
        //window.location.reload();
    };

    handleSubmit = () => {
        const {groupUpdate} = this.props;
        //console.log("update group props", this.props);
        //event.preventDefault();
        console.log("Submit", this.state);
        groupUpdate(
            {
                userName: sessionStorage.getItem('name'),
                email: sessionStorage.getItem('email'),
                password: sessionStorage.getItem('password'),
                id: this.state.id,
                name: this.state.name,
                city: this.state.city,
                groupInfo: this.state.groupInfo,
                memberNumber: this.state.memberNumber,
                peopleNumber: this.state.peopleNumber,
                rentalPeriod: this.state.rentalPeriod,
                free: this.state.free,
                members: this.state.members,
                applications: this.state.applications,
                polls: this.state.polls
            });
        //window.location.reload();
    };

    render() {
        let {
            type,
            isClick,
            group,
            showHeader,
            showAbout,
            showInfo,
            showMembers,
            user,
            adStyle
        } = this.props;
        const {id, name, city, rentalPeriod, members, peopleNumber, free, groupInfo} = group;
        type = this.state.groupBlockType;
        let isMember = this.isMember();
        let isApplicant = this.isApplicant();
        //console.log('group-block', this.state);
        return (

                <Box style={adStyle} className="group-block box-style">
                    {
                        showHeader &&

<Link to={`/group/${id}`}>{name}</Link>

                            {city}
                            <Link to={`/group/${id}`}>

                            </Link>

                    }
                    {
                        showAbout &&

"{groupInfo}"

                    }
                    {
                        showMembers && membersList(members)
                    }
                    {
                        showInfo &&

                            {(rentalPeriod === 1) && infoItem("Период аренды", "1 мес.")}
                            {(rentalPeriod === 3) && infoItem("Период аренды", "3 мес.")}
                            {(rentalPeriod === 6) && infoItem("Период аренды", "6 мес.")}
                            {(rentalPeriod === 9) && infoItem("Период аренды", "9 мес.")}
                            {(rentalPeriod === 12) && infoItem("Период аренды", "1 год")}
                            {(peopleNumber === 2) && infoItem("Всего", "2 места")}
                            {(peopleNumber === 3) && infoItem("Всего", "3 места")}
                            {(peopleNumber === 4) && infoItem("Всего", "4 места")}
                            {(peopleNumber === 5) && infoItem("Всего", "5 мест")}
                            {(peopleNumber === 6) && infoItem("Всего", "6 мест")}
                            {(free === 0) && infoItem("Осталось", "0 мест")}
                            {(free === 1) && infoItem("Осталось", "1 место")}
                            {(free === 2) && infoItem("Осталось", "2 места")}
                            {(free === 3) && infoItem("Осталось", "3 места")}
                            {(free === 4) && infoItem("Осталось", "4 места")}
                            {(free === 5) && infoItem("Осталось", "5 мест")}

                    }

                    {
                        (!isMember && !isApplicant) &&

                            <Button style={buttonStyle1} onClick={this.addApplication}>Подать заявку</Button>

                    }

                    {
                        (isMember || isApplicant) &&

                            <Button disabled>Заявка подана</Button>
                            <Button style={buttonStyle} onClick={this.deleteApplication}>Отменить</Button>

                    }

                    {
                        (!isMember && isApplicant) &&

Ваша заявка на рассмотрении!

                    }

                </Box>

        );
    }
}

GroupBlock.defaultProps = {showHeader: true, showAbout: true, showInfo: true, showMembers: true}
<file_sep>/src/components/faq-block/index.js
import FaqBlock from "./faq-block";

export default FaqBlock<file_sep>/src/components/promo-block/promo-block.js
import React from "react";
import "./promo-block.css";
import {withRouter} from 'react-router-dom';
import {Link} from "react-router-dom";

const PromoBlock = ({onAnchorClick, history}) => {
    const handleClick = () => {
        if (isAuthorized) {
            onAnchorClick();
        }
        else {
            history.push('/login');
        }
    }
    const isAuthorized=sessionStorage.getItem('isAuthorized');
    return (

Поиск сожителей стал гораздо проще

                Roomie решает все проблемы с поиском и находит сожителей по вашим критериям!

            <Link onClick={handleClick} className="promo-block-button">
                Начать поиск
            </Link>

    )
}

export default withRouter(PromoBlock);<file_sep>/src/pages/login.js
import React, {Component} from 'react'
import LoginForm from "../components/login-form";
import * as PropTypes from "prop-types";

class LoginPage extends Component {

    componentDidMount() {
        window.scrollTo(0, 0)
    }

    render() {
        let {login, authData} = this.props;
        const {error} = authData;
        return (

                <LoginForm login={login} authData={authData}/>
                {error &&
{error.toString()}
}

        );
    }
}

LoginPage.propTypes = {
    login: PropTypes.any,
    authData: PropTypes.any
}

export default LoginPage;<file_sep>/src/data.js
import {Component} from 'react';
import user1 from "./images/user1.png"
import {encode} from "base-64";

const COUNTRIES_URL ="http://api.roomie.kz/allcountries";
const LANGUAGES_URL ="http://api.roomie.kz/languages";
const ALMATY_UNI_URL = "http://api.roomie.kz/universities/183";
const ALL_GROUPS_URL = 'http://api.roomie.kz/allgroups';

export default class Data extends Component {

    _users = [
        "<NAME>",
        "<NAME>",
        "<NAME>",
        "<NAME>",
        "<NAME>",
        "<NAME>",
    ];
    _age = [20, 21, 22, 23, 24, 25];
    _groupNames = [
        "Студенты-физики",
        "Студенты-физики",
        "Студенты-физики",
        "Студенты-физики",
        "Студенты-физики",
        "Студенты-физики"
    ];
    _cities =[
        "Алматы",
        "Астана",
        "Костанай",
        "Атырау",
        "Алматы",
        "Алматы"
    ];
    _usersInfo = [
        "Люблю кошек и поспать",
        "Привет, я из Астаны, сейчас учусь в КБТУ, ищу сожительниц-девушек!",
        "Люблю “Очень странные дела”, фотографировать, учу испанский.",
        "Люблю “Очень странные дела”, фотографировать, учу испанский."
    ];

    _groupsInfo = [
        "Привет! Мы ищем таких же увлеченных физикой студентов!",
        "Мы ищем студентов МУИТ, хотим снять квартитру недалеко от нашего университета. У нас есть собака, и мы не против других питомцев :)",
        "Привет! Мы ищем таких же увлеченных физикой студентов!",
        "Мы ищем студентов МУИТ, хотим снять квартитру недалеко от нашего университета. У нас есть собака, и мы не против других питомцев :)",
        "Привет! Мы ищем таких же увлеченных физикой студентов!",
        "Мы ищем студентов МУИТ, хотим снять квартитру недалеко от нашего университета. У нас есть собака, и мы не против других питомцев :)"
    ];
    _free = [0, 2, 2, 1, 0, 1];
    _imgPath = user1;
    //_imgPath = "https://www.apicius.es/wp-content/uploads/2012/07/IMG-20120714-009211.jpg";
    _rentalPeriods = [1, 3, 6, 9, 12, 3];
    _peopleNumbers = [2, 3, 4, 4, 4, 3];
    //
    // createGroup = (id, name, city, rentalPeriod, peopleNumber, free, info, members, applications, polls) => {
    //     return {
    //         id: id,
    //         name: name,
    //         city: city,
    //         rentalPeriod: rentalPeriod,
    //         peopleNumber: peopleNumber,
    //         free: free,
    //         info: info,
    //         members: members,
    //         applications: applications,
    //         polls: polls
    //     };
    // };
    //
    _univercities = ["AlmaU", "Narxoz", "SDU", "MUIT", "KazNU", "KBTU"];
    _specialities = ["биолог", "физик", "математик", "геолог", "химик", "фезмот"];
    _languages = [["kz", "ru"], ["fr", "kx"], ["en", "gr"], ["ru"], ["sp"], ["aaaaaaa"]];
    _badHabits = [["курение", "алкоголь"], ["курение"], ["алкоголь"], [], [], []];
    _birthDates = ["4.07.1999", "4.07.1999", "4.07.1999", "4.07.1999", "4.07.1999", "4.07.1999"];
    _phoneNumbers = ["+7 777 777 77 77", "+7 777 777 77 77", "+7 777 777 77 77", "+7 777 777 77 77", "+7 777 777 77 77", "+7 777 777 77 77"];

    _questions = [
        {
            id: 1,
            question: "Как работает сервис Roomie?",
            answer: "Вы оставляете информацию о себе в форме регистрации, а мы предлагаем вам подходящие вам группы. Когда все настроено, можно начать эффективное использовании нашего сервиса и забыть о трудностях поиска сожителей! Но если найти подходящую группу все же не получилось, почему бы не создать свою?"
        },
        {
            id: 2,
            question: "Могу ли я создать свою группу для поиска сожителей?",
            answer: "Конечно! Зайдите на страницу профиля и спуститесь к списку своих групп. Обратите внимание, что там не будет необходимого вам блока создания группы, если вы уже состоите в одной! Чтобы создать новую группу, группа, в которой вы состоите, должна быть удалена, или, вы должны выйти из нее."
        },
        {
            id: 3,
            question: "Что делать, если у меня есть питомец?",
            answer: "Если вы волнуетесь, что это может доставить неудобства будущим сожителям, укажите это в поле дополнительной информации."
        },
        {
            id: 4,
            question: "Могу ли я воспользоваться Roomie, если я из другой страны?",
            answer: "К сожалению, сервис Roomie работает только в Казахстане. Но, если вы ищете жилье в городах Казахстана, то просто укажите страну и город рождения. Это также является одним из факторов, которые мы учитываем при подборе групп."
        },
        {
            id: 5,
            question: "Могу ли я найти сожителей на короткий срок?",
            answer: "При поиске сожителей на короткий срок, укажите, что планируете жить там менее одного месяца. Также, в дополнительной информации рекомендуем отметить более точные сроки."
        },
    ];

    _projectInfo = [
        {
            id: 1,
            question: "Как работают алгоритмы поиска?",
            answer: "Мы анализируем данные групп и данные, оставленные вами при регистрации и изменении профиля."
        },
        {
            id: 2,
            question: "Как улучшить качество поиска для меня?",
            answer: "Заполните максимальное количество полей при регистрации и изменении профиля, так мы сможем увеличить количество параметров поиска и подобрать группы, наиболее подходящие для вас."
        },
        {
            id: 3,
            question: "Почему я не могу быть участником нескольких групп?",
            answer: "Вы можете подавать заявки в несколько групп, но состоять будете только в одной. При добавлении в одну из групп как участника, все остальные заявки автоматически аннулируются."
        },
        {
            id: 4,
            question: "Как обрабатывается заявка на участие в группе?",
            answer: "При отправке заявки добавляется новое поле в опросах этой группы. В нем нынешние участники должны будут проголосовать за добавление нового участника. Если необходимое количество голосов набрано – вы становитесь участником."
        },
        {
            id: 5,
            question: "Как изменить фотографию профиля?",
            answer: "Зайдите на страницу профиля и нажмите на кнопку «изменить». Загрузите фотографию с устройства и не забудьте сохранить изменения."
        },
        {
            id: 6,
            question: "Другой пользователь указал недостоверную информацию. Что можно сделать?",
            answer: "Срочно сообщите нам! Свяжитесь с нами через электронную почту или по указанным номерам телефона. Мы заблокируем пользователя или свяжемся с ним самостоятельно."
        },
        {
            id: 7,
            question: "Зачем указывать столько личной информации?",
            answer: "Это поможет нам в более качественном подборе групп. Мы не используем вашу личную информацию и не имеем связей с заинтересованными лицами."
        },
        {
            id: 8,
            question: "Как принять в группу нового участника?",
            answer: "В первую очередь пользователь должен отправить заявку. После этого в опросах появится новый пункт, в котором участники группы проголосуют за принятие человека в группу, или, наоборот."
        },
        {
            id: 9,
            question: "Как удалить группу?",
            answer: "После нажатия на кнопку «удалить группу» на странице группы, появится опрос. Участники должны будут проголосовать за удаление."
        },
        {
            id: 10,
            question: "Как удалить страницу?",
            answer: "Зайдите на страницу профиля и нажмите на кнопку удаления профиля. Она находится справа на блоке информации. При появлении вопроса «удалить ли профиль?», ответьте положительно."
        },
    ];

    createUser = (id, name, age, city, info, birthDate, university, specialty, languages, badHabits, phoneNumber, groups) => {
        return {
            id: id,
            name: name,
            age: age,
            city: city,
            info: info,
            imgPath: this._imgPath,
            birthDate: birthDate,
            university: university,
            specialty: specialty,
            languages: languages,
            badHabits: badHabits,
            phoneNumber:phoneNumber
        };
    };

    getGroups = () => {
        const auth = sessionStorage.getItem('auth');
        return fetch(ALL_GROUPS_URL, {
            method: "GET",
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': auth,
            },
            //body: JSON.stringify({...credentials}),
        })
            .then(res => res.json())
            .then(res => {
            console.log("res " + JSON.stringify(res));
            const groups  = JSON.parse(res);
            console.log("fourps = " + JSON.stringify(groups));
            return groups;
        });
    };

    getGroup = (id) => {
        const auth = sessionStorage.getItem('auth');
        return fetch(`${ALL_GROUPS_URL}/${id}`, {
            method: "GET",
            mode: 'cors',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': auth,
            },
            //body: JSON.stringify({...credentials}),
        })
            .then(res => res.json())
            .then(res => {
                console.log("res " + JSON.stringify(res));
                const group  = JSON.parse(res);
                console.log("data group = " + JSON.stringify(group));
                return group;
            });
    };

    getCountries = async () => {
        //fetch(COUNTRIES_URL).then(response => response.json()).then(console.log);
        return fetch(COUNTRIES_URL, {method: 'GET'})
            .then(res => {return res.json()})
            .then(res => {
                const countries = JSON.parse(res).map((item) => {
                    //console.log("data data ", item);
                    return {label: item.name, value: item.name, id: item.id}
                });
                return countries
            })
    };

    getLanguages = async () => {
        //fetch(LANGUAGES_URL).then(response => response.json()).then(console.log);
        return fetch(LANGUAGES_URL, {method: 'GET'})
            .then(res => {return res.json()})
            .then(res => {
                const languages = JSON.parse(res).map((item) => {
                    //console.log("data data ", item);
                    return {label: item.lang_name, value: item.id, id: item.id}
                });
                //console.log("data lang", languages);
                return languages
            })
    };

    getCities = async (countryName) => {
        //console.log("dataaaa", countryName);
        return fetch(`http://api.roomie.kz/cities/${countryName}`, {method: 'GET'})
            .then(res => {return res.json()})
            .then(res => {
                const cities = JSON.parse(res).map((item) => {
                    //console.log("data data ", item);
                    return {label: item.name, value: item.id, id: item.id}
                });
                console.log("data cities", cities);
                return cities;
            });
    }

    getSpecialities = async ({universityId}) => {
        //console.log("dataaaa", countryName);
        return fetch(`http://api.roomie.kz/specialities/${universityId}`, {method: 'GET'})
            .then(res => {
                return res.json()
            })
            .then(res => {
                const specialities = JSON.parse(res).map((item) => {
                    //console.log("data data ", item);
                    return {label: item.name, value: item.id, id: item.id}
                });
                //console.log("data cities", cities);
                return specialities;
            });
    }

    getKazakhCities = async () => {
        //console.log("dataaaa", countryName);
        return fetch(`http://api.roomie.kz/cities/Казахстан`, {method: 'GET'})
            .then(res => {return res.json()})
            .then(res => {
                const cities = JSON.parse(res).map((item) => {
                    //console.log("data data ", item);
                    return {label: item.name, value: item.id, id: item.id}
                });
                //console.log("data cities", cities);
                return cities;
            })
    }

    getAlmatyUniversities = async () => {
        //fetch(LANGUAGES_URL).then(response => response.json()).then(console.log);
        return fetch(ALMATY_UNI_URL, {method: 'GET'})
            .then(res => {return res.json()})
            .then(res => {
                const almatyUniversities = JSON.parse(res).map((item) => {
                    //console.log("data data ", item);
                    return {label: item.name, value: item.id, id: item.id}
                });
                //console.log("data lang", languages);
                return almatyUniversities
            })
    };

    getUniversities = async ({cityId}) => {
        //console.log("dataaaa", countryName);
        return fetch(`http://api.roomie.kz/universities/${cityId}`, {method: 'GET'})
            .then(res => {return res.json()})
            .then(res => {
                const universities = JSON.parse(res).map((item) => {
                    //console.log("data data ", item);
                    return {label: item.name, value: item.id, id: item.id}
                });
                //console.log("data cities", cities);
                return universities;
            });
    }

    getUser = ({id}) => {
        const auth = sessionStorage.getItem('auth');
            return fetch(`http://api.roomie.kz/profile/${id}`, {
                method: "GET",
                mode: 'cors',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': auth,
                },
                //body: JSON.stringify({...credentials}),
            })
            .then(res => {return res.json()})
            .then(res => {
                let profile = JSON.parse(res);
                console.log("data ", profile);
                profile.languages = profile.languages.map((item) =>{
                     return item.languageName;
                });
                profile.languages = profile.languages.join(", ");
                if (profile.badHabits.length!==0)profile.badHabits = profile.badHabits[0].habitName;
                profile.university = profile.universityName;
                //profile.groups=[profile.ownedGroup];
                console.log("data profile", profile);
                return profile;
            })
    };

    getQuestions = () => this._questions;
    getProjectInfo = () => this._projectInfo;
}<file_sep>/src/components/create-group-form/create-group-form.js
import React, {Component} from "react";
import {Button, Control, Field, Input, Label} from "bloomer";
import Select from "react-select";
import {COUNTRIES} from "../../utils";
import {withRouter} from 'react-router-dom';
import './create-group-form.css';

const timePeriods = [
    { value: 1, label: '1 месяц' },
    { value: 3, label: 'до 3 месяцев' },
    { value: 6, label: 'до 6 месяцев' },
    { value: 9, label: 'до 9 месяцев' },
    { value: 12, label: 'больше' }
];

const peopleNumber = [
    { value: 2, label: '2' },
    { value: 3, label: '≤ 3' },
    { value: 4, label: '≤ 4' },
    { value: 5, label: '≤ 5' },
    { value: 6, label: 'больше' }
];

class CreateGroupForm extends Component {
    state = {
        groupName: '',
        city: '',
        peopleNeeded: '',
        rentalPeriod: '',
        telegramLink: '',
        whatsappLink: '',
        groupInfo: ''
    };

    handleInput = (key, value) => {
        this.setState({[key]: value} );
        console.log(this.state);
    };

    handleSubmit = (event) => {
        const {createGroup, history} = this.props;
        //console.log("create-group props", this.props);
        event.preventDefault();
        console.log("Submit", this.state);
        createGroup(
            {
                ownerId: sessionStorage.getItem('id'),
                name: this.state.groupName,
                cityId: this.state.city.value,
                maxNumOfRoommates: this.state.peopleNeeded.value,
                rentalPeriod: this.state.rentalPeriod.value,
                telegramLink: this.state.telegramLink,
                whatsappLink: this.state.whatsappLink,
                groupInfo: this.state.groupInfo
            });
        history.push('/');
    };

    render() {
        const {kazakhCities} = this.props;
        console.log("cities", kazakhCities);
        return (
            <form>
                <Field>
                    Название группы
                    <Control>
                        <Input type="text"
                               onChange={(event) => this.handleInput('groupName', event.target.value)}
                               placeholder='Студенты-физики'
                               isSize="medium"
                               className="mandatory-field-crate-group-form"
                               value={this.state.groupName}
                        />
                    </Control>
                </Field>
                <Field>
                    Количество человек в группе
                    <Control className="is-expanded">
                        <Select isSize="medium"
                                isSearchable
                                closeMenuOnSelect={true}
                                onChange={(value) => this.handleInput('peopleNeeded', value)}
                                options={peopleNumber}
                                className="is-fullwidth mandatory-field-crate-group-form"
                                value={this.state.peopleNeeded}
                        />
                    </Control>
                </Field>
                <Field>
                    Город
                    <Control className="is-expanded">
                        <Select isSize="medium"
                                isSearchable
                                closeMenuOnSelect={true}
                                onChange={(value) => this.handleInput('city', value)}
                                options={kazakhCities}
                                className="is-fullwidth mandatory-field-crate-group-form"
                                value={this.state.city}
                        />
                    </Control>
                </Field>
                <Field>
                    Период аренды
                    <Control className="is-expanded">
                        <Select isSize="medium"
                                isSearchable
                                closeMenuOnSelect={true}
                                onChange={(value) => this.handleInput('rentalPeriod', value)}
                                options={timePeriods}
                                className="is-fullwidth mandatory-field-crate-group-form"
                                value={this.state.rentalPeriod}
                        />
                    </Control>
                </Field>
                <Field>
                    Ссылка на беседу в Telegram
                    <Control>
                        <Input type="text"
                               onChange={(event) => this.handleInput('telegramLink', event.target.value)}
                               isSize="medium"
                               className="mandatory-field-crate-group-form"
                               value={this.state.telegramLink}
                        />
                    </Control>
                </Field>
                <Field>
                    Ссылка на беседу в Whats app
                    <Control>
                        <Input type="text"
                               onChange={(event) => this.handleInput('whatsappLink', event.target.value)}
                               isSize="medium"
                               className="mandatory-field-crate-group-form"
                               value={this.state.whatsappLink}
                        />
                    </Control>
                </Field>
                <Field>
                    Дополнительная информация
                    <Control>
                            <textarea  style={{"width": "100%"}}
                                       className="textarea"
                                       onChange={(event) => this.handleInput('groupInfo', event.target.value)}
                                       placeholder=''
                                       isSize="medium"/>
                    </Control>
                </Field>

                    <Button type="submit"
                            disabled={this.state.groupName==='' || this.state.city ==='' || this.state.peopleNeeded==='' || this.state.rentalPeriod==='' || this.state.telegramLink==='' || this.state.whatsappLink===''}
                            onClick={this.handleSubmit}
                            isColor='info'
                            style={{"width": "100%", "height": "54px"}}>
                        Готово!
                    </Button>

            </form>
        )
    }
}

export default withRouter(CreateGroupForm);<file_sep>/src/components/poll-list/poll-list.js
import React, {Component} from "react";
import Poll from "../poll";
import {Box} from "bloomer";
import './poll-list.css';

export default class PollList extends Component {
    state = {
        isBoxBottomHidden: true
    };
    render() {
        let {isBoxBottomHidden} = this.state;
        let {name, membersNumber, pollList, groupUpdate, group} = this.props;
        //console.log("PollList elements", pollList);
        const elements = pollList.map((item) => {
            const id = item.id;
            return (

                    <Poll form={item} groupUpdate={groupUpdate} group={group}/>

            );
        });

        return (

                <Box className="poll-box-style" onClick={() => this.setState({isBoxBottomHidden: !isBoxBottomHidden})}>

{name} ({membersNumber})

                </Box>
                <Box className="poll-container-style" isHidden={isBoxBottomHidden}>

                        {elements}

                </Box>

        );
    }
}<file_sep>/src/components/avatar/avatar.js
import React from "react"
import "./avatar.css"

const Avatar = ({size, image}) => {
    const style = {
        backgroundImage: `url(${image})`,
        backgroundRepeat: 'no-repeat',
        width: `${size}px`,
        height: `${size}px`
    }
    return(

    )
}

export default Avatar<file_sep>/src/components/create-group-form/index.js
import CreateGroupForm from "./create-group-form";

export default CreateGroupForm;<file_sep>/src/components/faq-block/faq-block-item/faq-block-item.js
import React, {Component} from "react";
import "./faq-block-item.css";
import { CSSTransition } from "react-transition-group";

export default class FaqBlockItem extends Component {

    state = { showAnswer: false }

    render() {
        const {item} = this.props;
        const {showAnswer} = this.state;
        return(

 this.setState({showAnswer: !showAnswer})}>

                        {item.question}

 this.setState({showAnswer: !showAnswer})}>

                    <CSSTransition
                        in={showAnswer}
                        timeout={200}
                        classNames="show-answer"
                        unmountOnExit
                        appear
                    >

{item.answer}

                    </CSSTransition>

        )
    }
}
<file_sep>/src/components/links-block/links-block.js
import React, {Component} from 'react';
import {Box, Image} from "bloomer";
import {Link} from "react-router-dom";
import telegram from "./../../images/telegram.svg"
import whatsapp from "./../../images/whatsapp.svg"
import './links-block.css'

const boxStyle = {
    background: "#FFFFFF",
    boxShadow: "0px 0px 48px rgba(0, 0, 0, 0.05)",
    borderRadius: "8px",
    width: "352px",
    padding: "36px 24px"
};

export default class LinksBlock extends Component {
    render() {
        const {telegramLink, whatsappLink} = this.props;
        return (

                <Box style={boxStyle} className="group-block">

Ссылки на беседы

                    <Link to={telegramLink} className="group-link">

Telegram

                    </Link>
                    <Link to={whatsappLink} className="group-link bottom-link">

WhatsApp

                    </Link>
                </Box>

        );
    }
}<file_sep>/src/pages/create-group.js
import React, {Component} from 'react';
import {Container, Section, Title} from "bloomer";
import CreateGroupForm from "../components/create-group-form/create-group-form";

const registerTitle = {
    "font-family": "Roboto",
    "font-style": "normal",
    "font-weight": "500",
    "font-size": "48px",
    "line-height": "56px",
    "text-align": "center",
    "letter-spacing": "0.25px",

    "color": "#000000"
};

class CreateGroupPage extends Component {

    componentDidMount() {
        window.scrollTo(0, 0)
    }

    render() {
        const {createGroup, kazakhCities} = this.props;
        return (
            <Container>

                    <Title style={registerTitle}
                           hasTextAlign="centered">
                        Создание группы
                    </Title>

                    <CreateGroupForm createGroup={createGroup} kazakhCities={kazakhCities}/>

            </Container>
        );
    }
}

export default CreateGroupPage;<file_sep>/src/utils/age-to-string.js
export const ageToString = (age) => {
    if (age % 100 >= 5 && age % 100 <= 20) {
        return `${age} лет`;
    }

    if (age % 10 === 1) {
        return `${age} год`;
    }

    if (age % 10 >= 2 && age % 10 <= 4) {
        return `${age} года`;
    }

    return `${age} лет`;
}<file_sep>/src/services/data-service.js
import React from 'react';

const COUNTRY =`api.roomie.kz/allcountries`;

<file_sep>/src/services/auth-service.js
import { encode } from "base-64";

const AUTH_URL =`http://api.roomie.kz/login`;
const SIGNUP_URL = `http://api.roomie.kz/register`;
const CREATE_GROUP_URL =`http://api.roomie.kz/creategroup`;
const UPDATE_USER_URL =`http://api.roomie.kz/user/:id`;
const UPDATE_GROUP_URL =`http://api.roomie.kz/profile/:id`;
const DELETE_USER_URL =`http://api.roomie.kz/profile/:id`;

export const signIn = async (credentials) => {
    const auth = 'Basic '+ encode(credentials.email + ":" + credentials.password);
    const result = await fetch(AUTH_URL, {
        method: "GET",
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': auth,
        },
        //body: JSON.stringify({...credentials}),
    });
    if (!result.ok) {
        console.log(result);
        throw new Error('Sign in failed');
    }
    sessionStorage.setItem('email', credentials.email);
    sessionStorage.setItem('password', <PASSWORD>);
    sessionStorage.setItem("auth", auth);
    return await result.json();
};

export const signUp = async (form) => {
    const auth = 'Basic '+ encode(form.email + ":" + form.password);
    console.log("form", form);
    const result = await fetch(SIGNUP_URL, {
        method: "POST",
        mode: 'cors',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({...form}),
    });
    if (!result.ok) {
        console.log(result);
        throw new Error(`Sign Up Failed`);
    }
    //console.log("register!!", result);
    sessionStorage.setItem('email', form.email);
    sessionStorage.setItem('password', <PASSWORD>);
    sessionStorage.setItem("auth", auth);
    return await result.json();
};

export const groupCreation = async (form) => {
    const auth = sessionStorage.getItem('auth');
    const result = await fetch(CREATE_GROUP_URL, {
        method: "POST",
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': auth,
        },
        body: JSON.stringify({...form}),
    });
    if (!result.ok) {
        console.log(result);
        throw new Error(`Group Creation Failed`);
    }
    return await result.json();
};

export const groupUpdate = async (form) => {
    const auth = sessionStorage.getItem('auth');
    const result = await fetch(UPDATE_GROUP_URL, {
        method: "PUT",
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': auth,
        },
        body: JSON.stringify({...form}),
    });
    if (!result.ok) {
        console.log(result);
        throw new Error(`User Update Failed`);
    }
    return await result.json();
};

export const userUpdate = async (form) => {
    const auth = sessionStorage.getItem('auth');
    const result = await fetch(UPDATE_USER_URL, {
        method: "PATCH",
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': auth,
        },
        body: JSON.stringify({...form}),
    });
    if (!result.ok) {
        console.log(result);
        throw new Error(`User Update Failed`);
    }
    return await result.json();
};

export const userDelete = async (credentials) => {
    const auth = sessionStorage.getItem('auth');
    const result = await fetch(DELETE_USER_URL, {
        method: "DELETE",
        mode: 'cors',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': auth,
        },
        body: JSON.stringify({...credentials}),
    });
    if (!result.ok) {
        console.log(result);
        throw new Error(`User Update Failed`);
    }
    return await result.json();
};<file_sep>/src/components/app-footer/app-footer.js
import React from 'react';

import './app-footer.css';
import {Column, Columns, Container} from "bloomer";

const AppFooter = () => {
    return (

                <Container>
                    <Columns className='container'>
                        <Column>

Roomie

                        </Column>
                        <Column>

                                Документы

                                Условия пользования

                                Политика конфиденциальности

                        </Column>
                        <Column>

Контакты

                                8 (705) 911 62 79

                                <EMAIL>

                        </Column>
                        <Column>

                                Мы в социальных сетях

Facebook

Instagram

                        </Column>
                    </Columns>
                </Container>

                <Container>
                    Roomie (c) 2019 All right
                </Container>

    );
};

export default AppFooter;<file_sep>/src/components/app-header/app-header.js
import React, {useState, useEffect} from 'react';
import {Container, Navbar, NavbarItem, NavbarBurger, NavbarBrand, NavbarMenu, NavbarStart, NavbarEnd} from "bloomer";
import "./app-header.css"
import {Link} from "react-router-dom";
import Avatar from "../avatar";
import camera from "./../../images/camera-black.svg";

const AppHeader = () => {

    const email = sessionStorage.getItem("email");
    const name = sessionStorage.getItem("name");
    const photo = sessionStorage.getItem("photo");
    const id = sessionStorage.getItem("id");
    const isAuthorized = sessionStorage.getItem("isAuthorized");
    //const password = sessionStorage.getItem("password");

    const [isActive, setIsActive] = useState(false);

    return (
        <Navbar>
            <Container>
                <NavbarBrand>
                    <NavbarItem>
                        <Link to="/">

Roomie

                        </Link>
                    </NavbarItem>
                    <NavbarBurger isActive={isActive} onClick={() => setIsActive(!isActive)}/>
                </NavbarBrand>
                <NavbarMenu isActive={isActive} onClick={() => setIsActive(false)}>
                    <NavbarStart>
                        <NavbarItem>
                            <Link to='/'>Главная</Link>
                        </NavbarItem>
                        <NavbarItem>
                            <Link to='/about'>О проекте</Link>
                        </NavbarItem>
                        <NavbarItem>
                            <Link to='/faq'>Часто задаваемые вопросы</Link>
                        </NavbarItem>
                    </NavbarStart>
                    {!isAuthorized &&
                    <NavbarEnd>
                        <NavbarItem>
                            <Link to="/login">Вход</Link>
                        </NavbarItem>
                        <NavbarItem>
                            <Link to="/register">Регистрация</Link>
                        </NavbarItem>
                    </NavbarEnd>
                    }
                    {isAuthorized &&
                    <NavbarEnd>
                        <NavbarItem>
                            <Link to={`/profile/${id}`}><Avatar image={photo==="undefined"?camera:photo} size={32} /></Link>
                            <Link to={`/profile/${id}`}>

{name}

                            </Link>
                        </NavbarItem>
                        <NavbarItem>
                            <Link to="/" onClick={() => {
                                sessionStorage.removeItem("name");
                                sessionStorage.removeItem("photo");
                                sessionStorage.removeItem('email');
                                sessionStorage.removeItem('password');
                                sessionStorage.removeItem('isAuthorized');
                                window.location.reload();
                            }}>

                            </Link>
                        </NavbarItem>

                    </NavbarEnd>
                    }

                </NavbarMenu>
            </Container>
        </Navbar>
    );
};

export default AppHeader;<file_sep>/src/components/promo-block/index.js
import PromoBlock from "./promo-block";

export default PromoBlock<file_sep>/src/components/menu.js
import React from 'react';
import {Link} from 'react-router-dom'

const Menu = () => {
    return (

<Link to={'/'}>Home</Link>

<Link to={'/faq'}>FAQ</Link>

<Link to={'/groups'}>Groups</Link>

<Link to={'/login'}>Login</Link>

<Link to={'/signup'}>Signup</Link>

<Link to={'/profile'}>Profile</Link>

    );
};

export default Menu;<file_sep>/src/components/profile-block/profile-block.js
import React, {Component} from 'react';
import { CSSTransition } from "react-transition-group";
import {Button, Input} from "bloomer";
import { withHelpersModifiers  } from 'bloomer';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

import './profile-block.css';
import Avatar from "../avatar";
import {ageToString} from "../../utils";
import Select from "react-select";
import {COUNTRIES} from "./../../utils/countries";
import {Link} from "react-router-dom";
import Data from "../../data";
import cameraBlack from './../../images/camera-black.svg';
import cameraWhite from './../../images/camera-white.svg';

const habits = [
    {value: "Нет", label: "Нет"},
    {value: "Курение", label: "Курение"},
    {value: "Алкоголь", label: "Алкоголь"},
    {value: "Курение и алкоголь", label: "Курение и алкоголь"}
];

const userProp = (key, value) => {
    return(

                {key}

                {value}

    )
};

const toBase64String = (type, data) => {
    return `data:${type};base64,${data}`;
};

class ProfileBlock extends Component {
    data=new Data();
    state = {
        id: this.props.user.id,
        photo: this.props.user.photo,
        name: this.props.user.name,
        age: this.props.user.age,
        sex: this.props.user.sex,
        currentCity: this.props.user.currentCity,
        birthCity: this.props.user.birthCity,
        birthDate: this.props.user.birthDate,
        university: this.props.user.university,
        specialty: this.props.user.speciality,
        languages: this.props.user.languages,
        badHabits: this.props.user.badHabits,
        phoneNumber: this.props.user.phoneNumber,
        userInfo: this.props.user.userInfo,
        maxRoommatesNumber: this.props.user.maxRoommatesNumber,
        rentalPeriod: this.props.user.rentalPeriod,
        showDetails: false,
        isChanging: false,
        specialities: []
    };

    notify = () => toast.error(this.toastMessage, {
        position: "bottom-center",
        autoClose: false,
        hideProgressBar: true,
        closeOnClick: false,
        pauseOnHover: true,
        draggable: true
    });

    toastMessage = () => {
        return (

Уверены, что хотите удалить аккаунт?

                <Link onClick={this.handleDelete} to={'/'}>Да</Link>

        );
    };

    editMode = () => {
        if (!this.state.isChanging) this.setState({showDetails: true});
        this.setState({isChanging: !this.state.isChanging});
    };

    handleDelete = (event) => {
        const {userDelete, history} = this.props;
        console.log("delete user props", this.props);
        event.preventDefault();
        console.log("Delete", this.state);
        userDelete(
            {
                email: sessionStorage.getItem('email'),
                password: sessionStorage.getItem('<PASSWORD>'),
                id: this.state.id,
            });
    };

    handleInput = (key, value) => {
        this.setState({[key]: value} );
        console.log("profile", this.state);
    };

    handleChangeImage = (event) => {
        const file = event.target.files[0];
        const reader = new FileReader();
        reader.addEventListener("load", () => (this.setState({photo: reader.result})));
        reader.readAsDataURL(file);
        //console.log("reader", reader.result)
    }

    handleSubmit = (event) => {
        const {userUpdate} = this.props;
        console.log("update user props", this.props);
        event.preventDefault();
        console.log("Submit", this.state);
        let lang = [...this.state.languages];
        lang= lang.map((item) => {return {id: item.id}});
        let badHabits = this.state.badHabits;
        if (badHabits.value != undefined) badHabits=badHabits.value;
        userUpdate(
            {
                email: sessionStorage.getItem('email'),
                password: sessionStorage.getItem('password'),
                photo: this.state.photo,
                id: this.state.id,
                userName: this.state.name,
                sex: this.state.sex,
                birthCountry: 'Казахстан',
                birthDate: this.state.birthDate,
                birthCity: this.state.birthCity,
                university: this.state.university,
                speciality: this.state.specialty,
                phoneNumber: this.state.phoneNumber,
                currentCity: this.state.currentCity,
                maxRoommatesNumber: this.state.maxRoommatesNumber,
                rentalPeriod: this.state.rentalPeriod,
                languages: lang,
                badHabits: badHabits,
                userInfo: this.state.userInfo,
                groups: this.state.groups
            });
        //window.location.reload();
    };

    getSpecialities = (universityId) => {
        this.data.getSpecialities({universityId})
        // .then(res => {
        //     console.log("getSpecialities", res);
        //     return res;
        // })
            .then(res => this.setState({specialities: res}))
        // .then(() => console.log("after", this.state.specialities));
    };

    handleChangeUniversity = (value) => {
        this.setState({university: value} );
        this.getSpecialities(value.value);
        //console.log("value", value);
        //console.log("handle cities", this.state.cities);
    }

    render() {
        let {showDetails, isChanging} = this.state;
        let {photo, age, languages, badHabits, birthDate, birthCity, currentCity, userInfo, name, phoneNumber, specialty, university} = this.state;
        const { almatyUniversities} = this.props;
        const allLanguages=this.props.languages;
        const isAuthorised = sessionStorage.getItem("email")?true:false;
        //console.log("profile-block coun", countries);
        return (

                <ToastContainer
                    position="bottom-center"
                    containerId={'A'}
                    autoClose={false}
                    newestOnTop={false}
                    closeOnClick
                    rtl={false}
                    pauseOnVisibilityChange
                    draggable
                />

                {
                    !isChanging &&

 this.setState({showDetails: !showDetails})}
                    >

                }
                {
                    !isChanging &&

                            <Avatar image={photo || cameraBlack} size={200}/>

{name}

{ageToString(age)}

                            {userProp('Родная страна', 'Казахстан', isChanging)}
                            {userProp('Родной город', birthCity, isChanging)}
                            <CSSTransition
                                in={showDetails}
                                timeout={300}
                                classNames="show-details"
                                unmountOnExit
                                appear
                            >

                                    {userProp('Дата рождения', birthDate, isChanging)}
                                    {userProp('Университет', university, isChanging)}
                                    {userProp('Специальность', specialty, isChanging)}
                                    {userProp('Языки', languages, isChanging)}
                                    {userProp('Вредные привычки', badHabits, isChanging)}
                                    {userProp('Телефон', phoneNumber, isChanging)}
                                    {userProp('О себе', userInfo, isChanging)}

                            </CSSTransition>

                }
                {
                    isChanging &&

                            <Avatar image={photo || cameraBlack} size={200}/>

                                <Input type='file' onChange={this.handleChangeImage}/>

                            <CSSTransition
                                in={showDetails}
                                timeout={300}
                                classNames="show-details"
                                unmountOnExit
                                appear
                            >

                                            ФИО

                                        <Input type="text"
                                               className="profile-change-value"
                                               onChange={(event) => this.handleInput('name', event.target.value)}
                                               placeholder='ФИО'
                                               isSize="medium"
                                               value={this.state.name}
                                        />

                                            Университет

                                        <Select isSize="medium"
                                                className="profile-change-value"
                                                isSearchable
                                                closeMenuOnSelect={true}
                                                onChange={(value) => {if (value!= undefined)this.handleChangeUniversity(value)}}
                                                options={almatyUniversities}
                                                value={this.state.university}
                                        />

                                            Специальность

                                        <Select isSize="medium"
                                                isSearchable
                                                className="profile-change-value"
                                                closeMenuOnSelect={true}
                                                onChange={(value) => {if (value!= undefined) this.handleInput('specialty', value)}}
                                                options={this.state.specialities}
                                                value={this.state.specialty}
                                        />

                                            Языки

                                        <Select isSize="medium"
                                                isMulti
                                                className="profile-change-value is-fullwidth"
                                                options={allLanguages}
                                                isSearchable
                                                closeMenuOnSelect={false}
                                                onChange={(value) => {if (value!= undefined) this.handleInput('languages', value)}}
                                                value={this.state.languages}
                                        />

                                            Вредные привычки

                                        <Select isSize="medium"
                                                isSearchable
                                                className="profile-change-value is-fullwidth"
                                                closeMenuOnSelect={true}
                                                onChange={(value) => {if (value!= undefined) this.handleInput('badHabits', value)}}
                                                options={habits}
                                                value={this.state.badHabits}
                                        />

                                            Телефон

                                        <Input type="tel"
                                               className="profile-change-value"
                                               onChange={(event) => this.handleInput('phoneNumber', event.target.value)}
                                               isSize="medium"
                                               value={this.state.phoneNumber}
                                               placeholder=''/>

                                            О себе

                                            <textarea className="profile-change-value textarea"
                                                      onChange={(event) => this.handleInput('userInfo', event.target.value)}
                                                      placeholder=''
                                                      value={this.state.info}
                                                      isSize="medium"/>

                            </CSSTransition>
                            <Button className="save-changes" type="submit" onClick={this.handleSubmit}>Сохранить изменения</Button>

                }

        );
    }
}

export default withHelpersModifiers(ProfileBlock);<file_sep>/src/components/users-list-item/users-list-item.js
import React from "react";
import {Content} from "bloomer";
import {Link} from "react-router-dom";
import camera from './../../images/camera-black.svg'

const UsersListItem = ({user}) => {
    const {userInfo, age, userCity, id, photo} = user;
    return (
        <Content isDisplay="flex">

                <Link to={`/profile/${id}`}>
                    {/* eslint-disable-next-line jsx-a11y/img-redundant-alt */}

                </Link>

{user.name}

{age}, {userCity}

                <Content>
                    {/*
Content
*/}

{userInfo}

                </Content>

        </Content>
    );
};

export default UsersListItem;<file_sep>/src/components/faq-block/faq-block.js
import React from "react"
import "./faq-block.css"
import FaqBlockItem from "./faq-block-item";

const FaqBlock = ({questions}) => {
    return(

            {questions.map(item => <FaqBlockItem key={item.id} item={item}/>)}

    )
}

export default FaqBlock<file_sep>/src/components/confetti-block/confetti-block.css
.confetti-block-controls {
    margin-top: 20px;
    display: flex;
    justify-content: space-around;
}

.confetti-block {
    display: flex;
    flex-direction: column;
    height: 450px;
    /*min-height: 478px;*/
}

.confetti {
    margin: 50px 100px;
    max-width: content-box;
    height: auto;
}

.confetti-title {
    font-family: Roboto;
    font-style: normal;
    font-weight: 500;
    font-size: 24px;
    line-height: 28px;
    text-align: center;
    letter-spacing: 0.25px;
    margin-bottom: 10px;

    color: #000000;
}

.confetti-title-afterword {
    font-family: Roboto;
    font-style: normal;
    font-weight: normal;
    font-size: 18px;
    line-height: 21px;

    /* identical to box height */
    text-align: center;
    letter-spacing: 0.25px;

    color: #000000;
}

.confetti-block-controls {

}<file_sep>/src/app.js
import React, {Component} from 'react';
import * as authService from "./services/auth-service"
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';

import './app.css';
import AppHeader from './components/app-header';
import AppFooter from './components/app-footer';
import HomePage from './pages/home';
import FAQPage from './pages/faq';
import GroupPage from './pages/group';
import LoginPage from './pages/login';
import RegisterPage from './pages/register';
import ProfilePage from './pages/profile';
import Data from './data';
import CreateGroupPage from "./pages/create-group";
import AboutPage from "./pages/about";

toast.configure();

export default class App extends Component {
    data = new Data();

    initialAuthData = {
        id: null,
        email: null,
        password: <PASSWORD>,
        loading: false,
        error: null
    };

    state = {
        groups: [],
        countries: [],
        languages: [],
        cities: [],
        almatyUniversities: [],
        kazakhCities: [],
        Auth: this.initialAuthData
    };

    setAuthData = ({id, email, password}) => {
        const newAuthData = {
            id, email, password, loading: false, error: null,
        };
        this.setState({Auth: newAuthData});
        console.log(this.state);
    };

    setAuthLoading = () => {
        const newAuthData = {...this.state.Auth, loading: true, error: null};
        this.setState({Auth: newAuthData})
    };

    setAuthError = (errorMessage) => {
        const newAuthData = {...this.state.Auth, loading: false, error: errorMessage};
        this.setState({Auth: newAuthData})
    };

    onError = (err) => {
        console.log("Error", err);
    };

    onGroupsLoaded = (groups) => {
        this.setState({
            groups: [...groups]
        });
    };

    getGroups = () => {
        this.data.getGroups()
            .then(groups => {
                this.onGroupsLoaded(groups);
            })
            .catch(this.onError)
    };

    onCountriesLoaded = (countries) => {
        this.setState({
            countries: [...countries]
        });
    };

    onLanguagesLoaded = (languages) => {
        this.setState({
            languages: [...languages]
        });
    };

    onKazakhCitiesLoaded = (kazakhCities) => {
        this.setState({
            kazakhCities: [...kazakhCities]
        });
    };

    onAlmatyUniversitiesLoaded = (almatyUniversities) => {
        this.setState({
            almatyUniversities: [...almatyUniversities]
        });
    };

    getCountries = () => {
        this.data.getCountries()
            .then(countries => {
                this.onCountriesLoaded(countries);
            })
            .catch(this.onError)
    };

    getLanguages = () => {
        this.data.getLanguages()
            .then(languages => {
                this.onLanguagesLoaded(languages);
            })
            .catch(this.onError)
    };

    getKazakhCities = () => {
        this.data.getKazakhCities()
            .then(kazakhCities => {
                this.onKazakhCitiesLoaded(kazakhCities);
            })
            .catch(this.onError)
    };

    getAlmatyUniversities = () => {
        this.data.getAlmatyUniversities()
            .then(almatyUniversities => {
                this.onAlmatyUniversitiesLoaded(almatyUniversities);
            })
            .catch(this.onError)
    };

    getUser = ({id}) => {
        this.data.getUser({id}).then(res => console.log("app getUser", res))
            .catch(this.onError);
    };

    componentDidMount() {
        this.getGroups();
        this.getCountries();
        this.getLanguages();
        this.getKazakhCities();
        this.getAlmatyUniversities();
    }

    register = (form) => {
        this.setAuthLoading();
        authService.signUp(form)
            .then(res => {
                let result = JSON.parse(res);
                console.log("app register ", result);
                const {id, name, photo} = result[0];
                sessionStorage.setItem('id', id);
                sessionStorage.setItem('photo', photo);
                sessionStorage.setItem('name', name);
                sessionStorage.setItem('isAuthorized', 'yes');
                this.setAuthData({id: id});
            })
            .catch(error => {
                console.log(error);
                this.setAuthError(error);
            })
    };

    login = (credentials) => {
        this.setAuthLoading();
        authService.signIn(credentials)
            .then(res => {
                let result = JSON.parse(res);
                console.log("res", result);
                const {id, name, photo} = result[0];
                sessionStorage.setItem('id', id);
                sessionStorage.setItem('photo', photo);
                sessionStorage.setItem('name', name);
                sessionStorage.setItem('isAuthorized', 'yes');
                this.setAuthData({id: id});
            })
            .catch(error => {
                console.log(error);
                this.setAuthError(error);
            })
    };

    userDelete = (credentials) => {
        this.setAuthLoading();
        authService.userDelete(credentials)
            .then(result => {
                sessionStorage.clear();
                console.log("deleted");
            })
            .catch(error => {
                console.log(error);
                this.setAuthError(error);
            })
    };

    createGroup = (form) => {
        this.setAuthLoading();
        authService.groupCreation(form)
            .then(result => {
                console.log("app createGroup ", result);
            })
            .catch(error => {
                console.log(error);
                this.setAuthError(error);
            })
    };

    userUpdate = (form) => {
        this.setAuthLoading();
        console.log("app userUpdate ", form);
        authService.userUpdate(form)
            .then((result) => {
                console.log("app userUpdate ", result);
                sessionStorage.setItem('photo', form.photo);
            })
            .catch(error => {
                console.log(error);
                this.setAuthError(error);
            })
    };

    groupUpdate = (form) => {
        this.setAuthLoading();
        console.log("app groupUpdate ", form);
        authService.userUpdate(form)
            .then(result => {
                console.log("app groupUpdate ", result);
            })
            .catch(error => {
                console.log(error);
                this.setAuthError(error);
            })
    };

    getGroupById = (id) => {
        let {groups} = this.state;
        const index = groups.findIndex(el => el.id === id);
        if (index > -1)
            return groups[index];
        return null;
    };

    apply = ({user, groupId}) => {
        const { groups } = this.state;
        let group = {};
        const index = groups.findIndex(g => g.id === groupId);
        if (index > -1) {
            group = groups[index];
            group.applications.push(user);
            const newGroups = [...groups.filter(g => g.id !== groupId), group];
            this.setState({groups: newGroups});
        }
    }

    cancel = ({userId, groupId}) => {
        const { groups } = this.state;
        let group = {};
        const index = groups.findIndex(g => g.id === groupId);
        if (index > -1) {
            group = groups[index];
            const newApplications = group.applications.filter(u => u.id !== userId);
            group.applications = newApplications;
            const newGroups = [...groups.filter(g => g.id !== groupId), group];
            this.setState({groups: newGroups});
        }
    }

    render() {
        let {groups, countries, languages, almatyUniversities, kazakhCities} = this.state;
        return (
            <Router>

                    <AppHeader/>
                    <Switch>
                        <Route exact path={'/'}
                               render = {() =>
                                   <HomePage
                                       cancel={this.cancel}
                                       apply={this.apply}
                                       groupUpdate={this.groupUpdate}
                                       groups={groups}
                                   />
                               }
                        />
                        <Route exact path={'/faq'}
                               render = {() => <FAQPage questions={this.data.getQuestions()}/>}
                        />
                        <Route exact path={'/group/:id'}
                               render ={({match}) => {
                                   //console.log("APP", this.getGroupById(parseInt(match.params.id)));
                                   return <GroupPage
                                       apply={this.apply}
                                       cancel={this.cancel}
                                       groupUpdate={this.groupUpdate}
                                       id={match.params.id}

                                       group={this.getGroupById(parseInt(match.params.id))}
                                   />
                               }}
                        />
                        <Route exact path={'/login'}
                            render = {() =>
                                <LoginPage
                                    authData={this.state.Auth}
                                    login={this.login}
                                />
                            }
                        />
                        <Route exact path={'/register'}
                               render = {() =>
                                   <RegisterPage
                                       countries={countries}
                                       register={this.register}
                                       languages={languages}
                                       kazakhCities={kazakhCities}
                                       almatyUniversities={almatyUniversities}
                                       num={"first"}
                                   />
                               }
                        />
                        <Route exact path={'/about'}
                               render = {() =>
                                   <AboutPage
                                       projectInfo={this.data.getProjectInfo()}
                                   />
                               }
                        />
                        <Route exact path={'/create-group'}
                               render = {() =>
                                   <CreateGroupPage
                                       kazakhCities={kazakhCities}
                                       createGroup={this.createGroup}
                                   />
                               }
                        />
                        <Route exact path={'/profile/:id'}
                               render = {({match}) =>
                                   <ProfilePage
                                       apply={this.apply}
                                       cancel={this.cancel}
                                       groupUpdate={this.groupUpdate}
                                       countries={countries}
                                       userUpdate={this.userUpdate}
                                       id={match.params.id}
                                       languages={languages}
                                       almatyUniversities={almatyUniversities}
                                       getUser = {this.data.getUser}
                                       userDelete={this.userDelete}
                                       //user={this.getUser(match.params.id)}
                                   />
                               }
                        />
                    </Switch>
                    <AppFooter/>

            </Router>
        );
    };
}<file_sep>/src/components/group-blocks/index.js
import GroupBlocks from './group-blocks';

export default GroupBlocks;

languages: JavaScript CSS

repo_name: newkater/roomie


text:
<file_sep>import string
import random

def remove_punctuation(var):
    no_punct = ""
    for item in var:
        if item not in string.punctuation:
            no_punct += item
    return no_punct

# no longer in use.
'''def lousy_plasma():
    empty_string = ""
    input1 = input("what is your sentence?").strip()
    input1 = remove_punctuation(input1).split( )
    for item in input1:
        if item in dict1.keys():
            empty_string += random.choice(dict1[item]).upper() + " "
        else:
            empty_string += item + " "
    print(empty_string)
    from os import system
    system("say -i -v Fiona " + "\"" + empty_string + "\"")'''

def word_changer(words):
    words = words.strip()
    words_without_punct = remove_punctuation(words).split()
    result = ""
    c = 0

    for item in words_without_punct:
        if item in dict1.keys():
            if c % 2 == 0:
                result += random.choice(dict1[item]).upper()

            else:
                result += item
            c += 1
        else:
            result += item
        result += " "
    return(result)

t = open('thesaurus', 'r')
dict1 = {}
for line in t:
    split_words = line.split(",")
    key = split_words.pop(0)
    dict1.update({key:split_words})

bad_blood_lyrics = open('bad_blood.txt', 'r')
lyrics = bad_blood_lyrics.read()

print(word_changer(lyrics))

branch_name: refs/heads/master

repo_language: Python