ocrcc-chatbox/src/components/ChatboxWithSettings.js

95 lines
2.4 KiB
JavaScript
Raw Normal View History

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import Chatbox from './chatbox';
2020-12-15 15:24:20 +00:00
const ChatboxWithSettings = ({ settingsEndpoint = null, matrixServerUrl, ...rest }) => {
const [settings, setSettings] = useState({});
2020-11-28 20:02:55 +00:00
const [shifts, setShifts] = useState();
const [isAvailable, setAvailability] = useState(true);
const getSettings = async () => {
const url = `${settingsEndpoint}?homeserver=${encodeURIComponent(matrixServerUrl)}`;
2020-12-15 15:24:20 +00:00
const res = await fetch(url);
const data = await res.json();
const { fields, schedule = [] } = data;
if (!fields) {
2020-10-20 23:29:12 +00:00
const props = {
...rest,
enabled: true,
2020-11-28 20:02:55 +00:00
isAvailable: true,
};
2020-10-20 23:29:12 +00:00
return setSettings(props);
}
2020-12-14 22:37:26 +00:00
const settingsObj = {};
2020-11-28 20:02:55 +00:00
setShifts(schedule);
Object.entries(fields).forEach(([k, v]) => {
const [scope, key] = k.split('_');
if (scope === 'web') {
settingsObj[key] = v;
}
});
2020-10-20 23:29:12 +00:00
if (!settingsObj.enabled) {
settingsObj.enabled = false;
}
return setSettings(settingsObj);
};
2020-11-28 20:02:55 +00:00
const checkSchedule = () => {
const weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const now = new Date();
const weekday = weekdays[now.getDay()];
const hours = now.getHours();
const minutes = now.getMinutes();
shifts.map(async (shift) => {
const [startHours, startMinutes] = shift.start.split(':').map((t) => Number(t));
const [endHours, endMinutes] = shift.end.split(':').map((t) => Number(t));
if (
shift.service === 'web'
&& shift.weekday === weekday
&& ((startHours < hours) || (startHours === hours && startMinutes <= minutes))
&& ((endHours > hours) || (endHours === hours && endMinutes > minutes))
) {
setAvailability(true);
}
});
};
useEffect(() => {
if (settingsEndpoint) {
getSettings();
}
}, [settingsEndpoint]);
2020-11-28 20:02:55 +00:00
useEffect(() => {
if (shifts && shifts.length > 0) {
2020-11-28 20:02:55 +00:00
checkSchedule();
}
}, [shifts]);
return (
2020-11-28 20:02:55 +00:00
/* eslint-disable react/jsx-props-no-spreading */
<Chatbox matrixServerUrl={matrixServerUrl} isAvailable={isAvailable} {...settings} {...rest} />
);
};
ChatboxWithSettings.propTypes = {
matrixServerUrl: PropTypes.string.isRequired,
settingsEndpoint: PropTypes.string,
};
ChatboxWithSettings.defaultProps = {
settingsEndpoint: null,
};
export default ChatboxWithSettings;