<commit_before>/*
 * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React, { useReducer, useState } from 'react';
import PropTypes from 'prop-types';
import TextField from '@material-ui/core/TextField';
import DialogContentText from '@material-ui/core/DialogContentText';
import { FormattedMessage, injectIntl } from 'react-intl';
import { makeStyles } from '@material-ui/core/styles';
import FormDialogBase from 'AppComponents/AdminPages/Addons/FormDialogBase';
import {
    Typography, RadioGroup, Radio, FormControlLabel, FormControl, Grid, Select, MenuItem,
} from '@material-ui/core';
import API from 'AppData/api';
import Alert from 'AppComponents/Shared/Alert';

const useStyles = makeStyles((theme) => ({
    error: {
        color: theme.palette.error.dark,
    },
    dialog: {
        minWidth: theme.spacing(150),

    },
    quotaHeading: {
        marginTop: theme.spacing(3),
        marginBottom: theme.spacing(2),
    },
    unitTime: {
        display: 'flex',
        minWidth: theme.spacing(60),
    },
    unitTimeSelection: {
        marginTop: theme.spacing(2.6),
        marginLeft: theme.spacing(2),
        minWidth: theme.spacing(15),
    },
}));

let initialState = {
    policyName: '',
    description: '',
    defaultLimit: {
        requestCount: '',
        timeUnit: 'min',
        unitTime: '',
        type: 'RequestCountLimit',
        dataAmount: '',
        dataUnit: 'KB',
    },
};


/**
 * Reducer
 * @param {JSON} state The second number.
 * @returns {Promise}
 */
function reducer(state, newValue) {
    const { field, value } = newValue;
    switch (field) {
        case 'policyName':
            return { ...state, [field]: value };
        case 'description':
            return { ...state, [field]: value };
        case 'requestCount':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'timeUnit':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'unitTime':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'type':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'dataAmount':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'dataUnit':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        default:
            return newValue;
    }
}

/**
 * Render a list
 * @returns {JSX} Header AppBar components.
 */
function AddEdit(props) {
    const classes = useStyles();
    const {
        updateList, icon, triggerButtonText, title, applicationThrottlingPolicyList, dataRow,
    } = props;
    const [state, dispatch] = useReducer(reducer, initialState);
    const {
        policyName, description, defaultLimit: {
            requestCount, timeUnit, unitTime, type, dataAmount, dataUnit,
        },
    } = state;
    const [validationError, setValidationError] = useState([]);
    const [editMode, setIsEditMode] = useState(false);
    const restApi = new API();

    const onChange = (e) => {
        dispatch({ field: e.target.name, value: e.target.value });
    };

    const validate = (fieldName, value) => {
        let error = '';
        switch (fieldName) {
            case 'policyName':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ policyName: error });
                break;
            case 'requestCount':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ requestCount: error });
                break;
            case 'dataAmount':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ dataAmount: error });
                break;
            case 'unitTime':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ unitTime: error });
                break;
            default:
                break;
        }
        return error;
    };

    const getAllFormErrors = () => {
        let errorText = '';
        const policyNameErrors = validate('policyName', policyName);
        const requestCountErrors = validate('requestCount', requestCount);
        const dataAmounttErrors = validate('dataAmount', dataAmount);
        const unitTimeErrors = validate('unitTime', unitTime);

        if (type === 'BandwidthLimit') {
            errorText += policyNameErrors + ' ' + dataAmounttErrors + ' ' + unitTimeErrors;
        } else {
            errorText += policyNameErrors + ' ' + requestCountErrors + ' ' + unitTimeErrors;
        }
        return errorText;
    };

    const formSaveCallback = () => {
        const formErrors = getAllFormErrors();
        if (formErrors !== '') {
            Alert.error(formErrors);
            return (false);
        }
        let applicationThrottlingPolicy;
        let promisedAddApplicationPolicy;

        if (type === 'BandwidthLimit') {
            delete (state.defaultLimit.requestCount);
            applicationThrottlingPolicy = state;
        } else {
            applicationThrottlingPolicy = delete (state.defaultLimit.dataUnit);
            applicationThrottlingPolicy = delete (state.defaultLimit.dataAmount);
            applicationThrottlingPolicy = state;
        }

        if (dataRow) {
            const selectedPolicy = applicationThrottlingPolicyList.filter(
                (policyy) => policyy.policyName === dataRow[0],
            );
            const policyId = selectedPolicy.length !== 0 && selectedPolicy[0].policyId;
            promisedAddApplicationPolicy = restApi.updateApplicationThrottlingPolicy(policyId,
                applicationThrottlingPolicy);<commit_msg>Remove space in error message<commit_after>/*
 * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you under the Apache License,
 * Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import React, { useReducer, useState } from 'react';
import PropTypes from 'prop-types';
import TextField from '@material-ui/core/TextField';
import DialogContentText from '@material-ui/core/DialogContentText';
import { FormattedMessage, injectIntl } from 'react-intl';
import { makeStyles } from '@material-ui/core/styles';
import FormDialogBase from 'AppComponents/AdminPages/Addons/FormDialogBase';
import {
    Typography, RadioGroup, Radio, FormControlLabel, FormControl, Grid, Select, MenuItem,
} from '@material-ui/core';
import API from 'AppData/api';
import Alert from 'AppComponents/Shared/Alert';

const useStyles = makeStyles((theme) => ({
    error: {
        color: theme.palette.error.dark,
    },
    dialog: {
        minWidth: theme.spacing(150),

    },
    quotaHeading: {
        marginTop: theme.spacing(3),
        marginBottom: theme.spacing(2),
    },
    unitTime: {
        display: 'flex',
        minWidth: theme.spacing(60),
    },
    unitTimeSelection: {
        marginTop: theme.spacing(2.6),
        marginLeft: theme.spacing(2),
        minWidth: theme.spacing(15),
    },
}));

let initialState = {
    policyName: '',
    description: '',
    defaultLimit: {
        requestCount: '',
        timeUnit: 'min',
        unitTime: '',
        type: 'RequestCountLimit',
        dataAmount: '',
        dataUnit: 'KB',
    },
};


/**
 * Reducer
 * @param {JSON} state The second number.
 * @returns {Promise}
 */
function reducer(state, newValue) {
    const { field, value } = newValue;
    switch (field) {
        case 'policyName':
            return { ...state, [field]: value };
        case 'description':
            return { ...state, [field]: value };
        case 'requestCount':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'timeUnit':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'unitTime':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'type':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'dataAmount':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        case 'dataUnit':
            return {
                ...state,
                defaultLimit: { ...state.defaultLimit, [field]: value },
            };
        default:
            return newValue;
    }
}

/**
 * Render a list
 * @returns {JSX} Header AppBar components.
 */
function AddEdit(props) {
    const classes = useStyles();
    const {
        updateList, icon, triggerButtonText, title, applicationThrottlingPolicyList, dataRow,
    } = props;
    const [state, dispatch] = useReducer(reducer, initialState);
    const {
        policyName, description, defaultLimit: {
            requestCount, timeUnit, unitTime, type, dataAmount, dataUnit,
        },
    } = state;
    const [validationError, setValidationError] = useState([]);
    const [editMode, setIsEditMode] = useState(false);
    const restApi = new API();

    const onChange = (e) => {
        dispatch({ field: e.target.name, value: e.target.value });
    };

    const validate = (fieldName, value) => {
        let error = '';
        switch (fieldName) {
            case 'policyName':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ policyName: error });
                break;
            case 'requestCount':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ requestCount: error });
                break;
            case 'dataAmount':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ dataAmount: error });
                break;
            case 'unitTime':
                error = value === '' ? (fieldName + ' is Empty') : '';
                setValidationError({ unitTime: error });
                break;
            default:
                break;
        }
        return error;
    };

    const getAllFormErrors = () => {
        let errorText = '';
        const policyNameErrors = validate('policyName', policyName);
        const requestCountErrors = validate('requestCount', requestCount);
        const dataAmounttErrors = validate('dataAmount', dataAmount);
        const unitTimeErrors = validate('unitTime', unitTime);

        if (type === 'BandwidthLimit') {
            errorText += policyNameErrors + dataAmounttErrors + unitTimeErrors;
        } else {
            errorText += policyNameErrors + requestCountErrors + unitTimeErrors;
        }
        return errorText;
    };

    const formSaveCallback = () => {
        const formErrors = getAllFormErrors();
        if (formErrors !== '') {
            Alert.error(formErrors);
            return (false);
        }
        let applicationThrottlingPolicy;
        let promisedAddApplicationPolicy;

        if (type === 'BandwidthLimit') {
            delete (state.defaultLimit.requestCount);
            applicationThrottlingPolicy = state;
        } else {
            applicationThrottlingPolicy = delete (state.defaultLimit.dataUnit);
            applicationThrottlingPolicy = delete (state.defaultLimit.dataAmount);
            applicationThrottlingPolicy = state;
        }

        if (dataRow) {
            const selectedPolicy = applicationThrottlingPolicyList.filter(
                (policyy) => policyy.policyName === dataRow[0],
            );
            const policyId = selectedPolicy.length !== 0 && selectedPolicy[0].policyId;
            promisedAddApplicationPolicy = restApi.updateApplicationThrottlingPolicy(policyId,
                applicationThrottlingPolicy);
{'fraction_non_alphanumeric': 0.12103703703703704, 'fraction_numerical': 0.003851851851851852, 'mean_word_length': 2.0635352847742228, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7157036', 'n_tokens_mistral': 3567, 'n_tokens_neox': 3480, 'n_words': 919}