/*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, { useState, useEffect } from 'react'
import LoadingSpinner from '../../LoadingSpinner.js'
import Template from '../PanelComponents/TemplateRecurso.js'
import TemplateCuradoria from '../PanelComponents/TemplateCuradoria.js'
import { fetchAllRequest, getRequest } from '../../HelperFunctions/getAxiosConfig'

export default function TabPanelAtividades(props) {
    const [loading, handleLoading] = useState(true)

    const [errorInLearnObj, setErrorInLearnObj] = useState(false)
    const [errorInDrafts, setErrorInDrafts] = useState(false)
    const [errorInCurating, setErrorInCurating] = useState(false)

    const [loadingMoreLearnObj, setLoadingMoreLearnObj] = useState(false)
    const [loadingMoreDrafts, setLoadingMoreDrafts] = useState(false)
    const [loadingMoreCurating, setLoadingMoreCurating] = useState(false)

    const [currLimitLearnObj, setCurrLimitLearnObj] = useState(4);
    const [currLimitDrafts, setcurrLimitDrafts] = useState(4);
    const [currLimitCurating, setcurrLimitCurating] = useState(4);

    const [endOfLearnObj, setEndofLearndObj] = useState(0);
    const [endOfDrafts, setEndofDrafts] = useState(0);
    const [endOfCurating, setEndofCurating] = useState(0);

    const [learningObjects, setLearningObjects] = useState([]);
    const [drafts, setDrafts] = useState([]);
    const [curating, setCurating] = useState([]);

    function handleSuccess(responseArr, headersArr) {
        setErrorInLearnObj(responseArr[0].errors ? true : false)
        setErrorInDrafts(responseArr[1].errors ? true : false)
        setErrorInCurating(responseArr[2].errors ? true : false)

        setLearningObjects(responseArr[0])
        if (headersArr[0].has('X-Total-Count')) {
            setEndofLearndObj(headersArr[0].get('X-Total-Count'));
        }

        setDrafts(responseArr[1])
        if (headersArr[1].has('X-Total-Count')) {
            setEndofDrafts(headersArr[1].get('X-Total-Count'));
        }

        setCurating(responseArr[2])
        if (headersArr[2].has('X-Total-Count')) {
            setEndofCurating(headersArr[2].get('X-Total-Count'));
        }

        handleLoading(false)

    }

    function handleError(error) {
        handleLoading(false)
        setErrorInCurating(true)
        setErrorInDrafts(true)
        setErrorInLearnObj(true)
    }

    useEffect(() => {
        const urls = [
            `/users/${props.id}/learning_objects?offset=0&limit=4`,
            `/users/${props.id}/drafts?offset=0&limit=4`,
            `/users/${props.id}/submissions?offset=0&limit=4&status=submitted`
        ]
        handleLoading(true);
        fetchAllRequest(urls, handleSuccess, handleError)
    }, [])

    const showMoreLearnObj = (limite) => {
        setLoadingMoreLearnObj(true);
        const limit = limite;
        setCurrLimitLearnObj(currLimitLearnObj + limit)
        const url = `/users/${props.id}/learning_objects?offset=${currLimitLearnObj}&limit=${limit}`;
        getRequest(url,
            (data) => {
                if (data.errors) {
                    setLoadingMoreLearnObj(false);
                    setErrorInLearnObj(true)
                }
                else if (data.length >= 1) {
                    let currData = [...learningObjects];
                    currData = [...currData.concat(data)];
                    setLoadingMoreLearnObj(false);
                    setLearningObjects(currData);
                }
                else {
                    setLoadingMoreLearnObj(false);
                }
            },
            (error) => {
                setLoadingMoreLearnObj(false);
                setErrorInLearnObj(true)
            }
        )
    }

    const showMoreDrafts = (limite) => {
        setLoadingMoreDrafts(true);
        console.log(limite);
        const limit = limite;
        setcurrLimitDrafts(currLimitDrafts + limit)
        const url = `/users/${props.id}/drafts?offset=${currLimitDrafts}&limit=${limit}`;
        getRequest(url,
            (data) => {
                if (data.errors) {
                    setLoadingMoreDrafts(false);
                    setErrorInDrafts(true)
                }
                else if (data.length >= 1) {
                    let currData = [...drafts];
                    currData = [...currData.concat(data)];
                    console.log('drafs: ', currData);
                    setLoadingMoreDrafts(false);
                    setDrafts([...currData]);
                }
                else {
                    setLoadingMoreDrafts(false);
                }
            },
            (error) => {
                setLoadingMoreDrafts(false);
                setErrorInDrafts(true)
            }
        )
    }

    const showMoreCurating = (limite) => {
        setLoadingMoreCurating(true);
        const limit = limite;
        setcurrLimitCurating(currLimitCurating + limit)
        const url = `/users/${props.id}/submissions?offset=${currLimitCurating}&limit=${limit}&state=submitted`;
        getRequest(url,
            (data) => {
                if (data.errors) {
                    setLoadingMoreCurating(false);
                    setErrorInCurating(true);
                }
                else if (data.length >= 1) {
                    let currData = [...curating];
                    currData = [...currData.concat(data)];
                    setLoadingMoreCurating(false);
                    setCurating([...currData]);
                }
                else {
                    setLoadingMoreCurating(false);
                }

            },
            (error) => {
                setLoadingMoreCurating(false);
                setErrorInCurating(true);
            }
        )
    }

    return (
        <>
            {
                loading ?
                    (
                        <LoadingSpinner contrast={props.contrast} text={'Carregando Recursos'} />
                    )
                    :
                    (
                        [
                            <React.Fragment>
                                <Template
                                    contrast={props.contrast}
                                    length={learningObjects.length}
                                    titleText={learningObjects.length === 1 ? "Recurso Publicado" : "Recursos Publicados"}
                                    noContentText={"Você ainda não publicou nenhum Recurso!"}
                                    slice={learningObjects}
                                    showMore={showMoreLearnObj}
                                    loadingMore={loadingMoreLearnObj}
                                    end={endOfLearnObj}
                                    error={errorInLearnObj}
                                />

                                <Template
                                    contrast={props.contrast}
                                    length={drafts.length}
                                    titleText={drafts.length === 1 ? "Rascunho Publicado" : "Rascunhos Publicados"}
                                    noContentText={"Você não tem nenhum recurso sendo editado."}
                                    slice={drafts}
                                    showMore={showMoreDrafts}
                                    loadingMore={loadingMoreDrafts}
                                    end={endOfDrafts}
                                    error={errorInDrafts}
                                />

                                <TemplateCuradoria
                                    contrast={props.contrast}
                                    length={curating.length}
                                    titleText={curating.length === 1 ? "Recurso sendo avaliado pela curadoria" : "Recursos sendo avaliados pela curadoria"}
                                    noContentText={"Você não tem nenhum recurso sendo avaliado pelos curadores."}
                                    sliceArr={curating}
                                    showMore={showMoreCurating}
                                    loadingMore={loadingMoreCurating}
                                    end={endOfCurating}
                                    error={errorInCurating}
                                />
                            </React.Fragment>
                        ]
                    )
            }
        </>
    )
}