From d87ca25c1b16a70380a28d21c1f45fe5a7a2710c Mon Sep 17 00:00:00 2001
From: Luis Felipe Risch <lfr20@inf.ufpr.br>
Date: Tue, 3 Nov 2020 12:38:37 -0300
Subject: [PATCH] File to display data from Languages

---
 src/Admin/Pages/Pages/SubPages/Languages.js | 350 ++++++++++++++++++++
 1 file changed, 350 insertions(+)
 create mode 100644 src/Admin/Pages/Pages/SubPages/Languages.js

diff --git a/src/Admin/Pages/Pages/SubPages/Languages.js b/src/Admin/Pages/Pages/SubPages/Languages.js
new file mode 100644
index 00000000..b27b5e58
--- /dev/null
+++ b/src/Admin/Pages/Pages/SubPages/Languages.js
@@ -0,0 +1,350 @@
+/*Copyright (C) 2019 Centro de Computacao Cientifica e Software Livre
+Departamento de Informatica - Universidade Federal do Parana
+
+This file is part of Plataforma Integrada MEC.
+
+Plataforma Integrada MEC is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as published by
+the Free Software Foundation, either version 3 of the License, or
+(at your option) any later version.
+
+Plataforma Integrada MEC is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+GNU Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with Plataforma Integrada MEC.  If not, see <http://www.gnu.org/licenses/>.*/
+
+import React, { useEffect, useState } from 'react'
+//imports from local files 
+import TableData from '../../../Components/Components/Table';
+import SnackBar from '../../../../Components/SnackbarComponent';
+import AlertDialog from "../../../Components/Components/AlertDialog";
+import CreateLanguage from '../../../Components/Components/Inputs/CreateLanguage';
+import EditLanguage from '../../../Components/Components/Inputs/EditLanguage';
+import { Url } from '../../../Filters';
+import { GetFullList, Delete } from '../../../Services';
+import { DeleteFilter } from '../../../Filters';
+//imports from material ui 
+import { withStyles } from '@material-ui/core/styles';
+import TableBody from '@material-ui/core/TableBody';
+import TableCell from '@material-ui/core/TableCell';
+import TableRow from '@material-ui/core/TableRow';
+import IconButton from '@material-ui/core/IconButton';
+import { Button, Typography, Paper, Grid } from '@material-ui/core';
+import CircularProgress from '@material-ui/core/CircularProgress';
+import AddRoundedIcon from '@material-ui/icons/AddRounded';
+import UpdateRoundedIcon from '@material-ui/icons/UpdateRounded';
+import EditRoundedIcon from '@material-ui/icons/EditRounded';
+import DeleteRoundedIcon from '@material-ui/icons/DeleteRounded';
+
+let currPage = 0;
+let editItem = {};
+
+const StyledTableCell = withStyles((theme) => ({
+    head: {
+        backgroundColor: theme.palette.common.black,
+        color: theme.palette.common.white,
+    },
+    body: {
+        fontSize: 14,
+    },
+}))(TableCell);
+
+const StyledTableRow = withStyles((theme) => ({
+    root: {
+        '&:nth-of-type(odd)': {
+            backgroundColor: theme.palette.action.hover,
+        },
+    },
+}))(TableRow);
+
+const Languages = () => {
+    const ADD_ONE_LENGHT = [""];
+    const TOP_LABELS = ['ID', 'Nome', 'Code', 'Editar', 'Deletar'] //Labels from Table  
+
+    const [error, setError] = useState(null); //Necessary to consult the API, catch errors
+    const [isLoaded, setIsLoaded] = useState(false); //Necessary to consult the API, wait until complete
+    const [items, setItems] = useState([]); //Necessary to consult the API, data 
+
+    const [isLoadingMoreItems, setIsLoadingMoreItems] = useState(false) //controlls the state of loadind more data
+    const [isUpdating, setIsUpdating] = useState(false); //controlls the state of updating data
+    const [openAlertDialog, setOpenAlertDialog] = useState(false); //controlls the state od alert dialog 
+
+    const [deleteItem, setDeleteItem] = useState({}); //Delete Item
+    const [isLoadingToDelete, setIsLoadingToDelete] = useState(null);
+
+    const [createLanguage , setCreateLanguage] = useState(false);
+    
+    const [editLanguage , setEditLanguage] = useState(false);
+
+    const [snackInfo, setSnackInfo] = useState({
+        message: '',
+        icon: '',
+        open: false,
+        color: '',
+    })
+
+    //handle snack info
+    const HandleSnack = (message, state, icon, color) => {
+        setSnackInfo({
+            message: message,
+            icon: icon,
+            open: state,
+            color: color
+        })
+    }
+
+    //handle load more items
+    const LoadMoreItens = async (api) => {
+        setIsLoadingMoreItems(true)
+        GetFullList(api).then(res => {
+            if (res.state) {
+                const arrData = [...res.data]
+                if (arrData.length === 0) {
+                    HandleSnack('Não há mais dados para serem carregados', true, 'warning', '#FFC125')
+                } else {
+                    const arrItems = [...items]
+                    arrItems.pop(); //Deleting the last position, that was used to display the button of load more items 
+                    const arrResult = arrItems.concat(arrData)
+                    setItems(arrResult.concat(ADD_ONE_LENGHT))
+                }
+
+            } else {
+                HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072')
+            }
+            setIsLoadingMoreItems(false)
+        })
+    }
+
+    // handle update list data
+    const UpdateHandler = async (api) => {
+        setIsUpdating(true)
+        GetFullList(api).then(res => {
+            if (res.state) {
+                HandleSnack('A lista de dados foi atualizada', true, 'success', '#228B22')
+                const arrData = [...res.data]
+                setItems(arrData.concat(ADD_ONE_LENGHT))
+            } else {
+                HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072')
+            }
+            setIsUpdating(false)
+        })
+    }
+
+    //handle Delete
+    async function DeleteHandler() {
+        const id = deleteItem.id;
+        HandleStateAlertDialog(null);
+        Delete(DeleteFilter("languages", id)).then((res) => {
+            if (res) {
+                HandleSnack(
+                    "A língua foi deletada com sucesso",
+                    true,
+                    "success",
+                    "#228B22"
+                );
+                currPage = 0;
+                // transformListToAsc = false
+                UpdateHandler(Url("languages", "", `${currPage}`, "DESC"));
+            } else {
+                HandleSnack("Ocorreu algum erro", true, "warning", "#FA8072");
+            }
+            HandleStateCircularProgress(null);
+        });
+    }
+
+    const HandleStateCircularProgress = (i) => {
+        setIsLoadingToDelete(i);
+    };
+
+    const HandleStateAlertDialog = (i) => {
+        const obj = { ...items[i] };
+        setDeleteItem(obj);
+        setOpenAlertDialog(!openAlertDialog);
+    }; 
+
+    const HandleEditLanguage = (i) => {
+        editItem = {...items[i]}
+        setEditLanguage(true)
+    }
+
+    //getting data from server
+    useEffect(() => {
+        fetch(Url('languages', '', `${currPage}`, 'DESC'))
+            .then(res => res.json())
+            .then(
+                (result) => {
+                    setIsLoaded(true);
+                    setItems(result.concat(ADD_ONE_LENGHT));
+                },
+                (error) => {
+                    setIsLoaded(true);
+                    // HandleSnack('Erro ao carregar os dados', true, 'warning', '#FA8072')
+                    setError(error);
+                }
+            )
+    }, []);
+
+
+    if (error) {
+        return <div>Error: {error.message}</div>;
+    } else if (!isLoaded) {
+        return <div>Loading...</div>;
+    } else {
+        return (
+            createLanguage ?
+                <CreateLanguage
+                    BackToList={() => setCreateLanguage(false)}
+                    UpdateList={UpdateHandler}
+                />
+
+                :
+                
+                editLanguage ? 
+                <EditLanguage
+                    editInfo={editItem} 
+                    UpdateList={UpdateHandler}
+                    BackToList={() => setEditLanguage(false)}
+                /> 
+                
+                : 
+                <>
+                    <SnackBar
+                        severity={snackInfo.icon}
+                        text={snackInfo.message}
+                        snackbarOpen={snackInfo.open}
+                        color={snackInfo.color}
+                        handleClose={() => setSnackInfo({
+                            message: '',
+                            icon: '',
+                            open: false,
+                            color: ''
+                        })}
+                    />
+
+                    <Paper style={{ padding: '1em' }}>
+                        <Grid container spacing={3} direction="row" alignItems="center">
+                            <Grid item xs={6}>
+                                <Typography variant="h4">
+                                    Linguagens
+                            </Typography>
+                            </Grid>
+                            <Grid
+                                item
+                                xs={6}
+                                alignItems="center"
+                                justify="center"
+                                direction="row"
+                            >
+                                <Grid container justify="flex-end" spacing={3}>
+                                    <Grid item>
+                                        <Button
+                                            variant="contained"
+                                            color="secondary"
+                                            disabled={isUpdating}
+                                            onClick={() => {
+                                                currPage = 0
+                                                UpdateHandler(Url('languages', '', `${currPage}`, 'DESC'))
+                                            }}
+                                            startIcon={<UpdateRoundedIcon />}
+                                        >
+                                            {
+                                                isUpdating ? <CircularProgress size={24} /> : 'Atualizar'
+                                            }
+                                        </Button>
+                                    </Grid>
+                                    <Grid item>
+                                        <Button
+                                            variant="contained"
+                                            color="secondary"
+                                            onClick={() => {
+                                                currPage = 0
+                                                setCreateLanguage(true)
+                                            }}
+                                            startIcon={<AddRoundedIcon />}
+                                        >
+                                            Novo
+                                    </Button>
+                                    </Grid>
+                                </Grid>
+                            </Grid>
+                        </Grid>
+                    </Paper>
+
+                    <div style={{ height: '2em' }}></div>
+
+                    <TableData
+                        top={TOP_LABELS}
+                    >
+                        <TableBody>
+                            {items.map((row, index) => (
+                                index === items.length - 1 ?
+                                    <div style={{ padding: '1em' }}>
+                                        {/* Button to load more data */}
+                                        <Button
+                                            color='primary'
+                                            variant='text'
+                                            // disabled={isLoadingMoreItems}
+                                            startIcon={<AddRoundedIcon />}
+                                            disabled={isLoadingMoreItems}
+                                            onClick={() => {
+                                                currPage++
+                                                LoadMoreItens(Url('languages', '', `${currPage}`, 'DESC'))
+                                            }}
+                                        >
+                                            {
+                                                isLoadingMoreItems ? <CircularProgress size={24} /> : 'Carregar mais itens'
+                                            }
+                                        </Button>
+                                    </div>
+
+                                    :
+
+                                    <StyledTableRow key={index}>
+                                        <StyledTableCell component="th" scope="row">{row.id}</StyledTableCell>
+                                        <StyledTableCell align="right">{row.name}</StyledTableCell>
+                                        <StyledTableCell align="right">{row.code}</StyledTableCell>
+                                        <StyledTableCell align="right">
+                                            <IconButton onClick={() => {
+                                                currPage = 0
+                                                HandleEditLanguage(index)
+                                            }}>
+                                                <EditRoundedIcon style={{ fill: '#00bcd4' }} />
+                                            </IconButton>
+                                        </StyledTableCell>
+                                        <StyledTableCell align="right">
+                                            {isLoadingToDelete === index ? (
+                                                <CircularProgress size={24} color="primary" />
+                                            ) : (
+                                                    <IconButton
+                                                        onClick={() => {
+                                                            HandleStateAlertDialog(index);
+                                                            HandleStateCircularProgress(index);
+                                                        }}
+                                                    >
+                                                        <DeleteRoundedIcon style={{ fill: "#FF0000" }} />
+                                                    </IconButton>
+                                                )}
+                                        </StyledTableCell>
+                                    </StyledTableRow>
+                            ))}
+                        </TableBody>
+                    </TableData>
+
+                    {/* This alert will be displayed if the user click to delete an institution */}
+                    <AlertDialog
+                        open={openAlertDialog}
+                        OnDelete={DeleteHandler}
+                        deleteItem={deleteItem}
+                        HandleClose={() => {
+                            setOpenAlertDialog(false);
+                            HandleStateCircularProgress(null);
+                        }}
+                    />
+                </>
+        );
+    }
+}
+export default Languages;
\ No newline at end of file
-- 
GitLab