/*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 styled from 'styled-components'
import Grid from '@material-ui/core/Grid';
import LoadingSpinner from '../../LoadingSpinner.js'
import axios from 'axios'
import {apiUrl} from '../../../env';
import PanelTemplateColecao from '../PanelComponents/TemplateColecao.js'
import PaginaVaziaColecao from '../../../img/Pagina_vazia_colecao.png'

import NoContent from '../PanelComponents/NoContent.js'
import {WhiteContainer, StyledGrid} from '../StyledComponents.js'
import CreateNewFolderIcon from '@material-ui/icons/CreateNewFolder';
import Title from '../PanelComponents/PanelTitle.js'
import CollectionCardFunction from '../../CollectionCardFunction.js'
import {ButtonsAreaColecao} from '../PanelComponents/ButtonsArea'


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

    const [userCollections, setUserCollections] = useState([])
    const [userCollectionsSlice, setUserCollectionsSlice] = useState([])

    const [followedCollections, setFollowedCollections] = useState([])
    const [followedCollectionsSlice, setFollowedCollectionsSlice] = useState([])

    useEffect( () => {
        axios.all([
            axios.get((`${apiUrl}/users/` + props.id + '/collections'), props.config),
            axios.get((`${apiUrl}/users/` + props.id + '/following/Collection'), props.config),
        ])
        .then( (responseArr) => {
                console.log('responseArr Colecoes: ', responseArr)
                if (responseArr[0].headers['access-token']) {
                    sessionStorage.setItem('@portalmec/accessToken', responseArr[0].headers['access-token'])
                }

                handleLoading(false)
                setUserCollections(responseArr[0].data)
                setUserCollectionsSlice(responseArr[0].data.slice(0,3))

                setFollowedCollections(responseArr[1].data)
                setFollowedCollectionsSlice(responseArr[1].data.slice(0,4))

            },
            (error) => {
                handleLoading(false)
                console.log('error while running axios all')
            }
        )
    }, [])

    const showMoreUserCollections = () => {
        var sliceLength = userCollectionsSlice.length
        setUserCollectionsSlice(userCollections.slice(0, sliceLength + 4))
    }

    const showAllUserCollections = () => {setUserCollectionsSlice(userCollections)}

    const showMoreFollowedCollections = () => {
        var sliceLength = followedCollectionsSlice.length
        setFollowedCollectionsSlice(followedCollections.slice(0, sliceLength + 4))
    }

    const showAllFollowedCollections = () => {setFollowedCollectionsSlice(followedCollections)}


    return (
        <>
        {
            loading ?
            (
                <LoadingSpinner text={'CARREGANDO COLEÇÕES'}/>

            )
            :
            (
                [
                    <React.Fragment>
                        <Tentativa
                            title={"Minhas Coleções"}
                            length={userCollections.length}
                            noContentText={
                                <div>
                                    <img src={PaginaVaziaColecao} alt="PaginaVaziaColecao" style={{height:"150px",width:"150px", verticalAlign:"middle", border:"0"}}/>
                                    <br/>
                                    <span style={{fontFamily:"Roboto", fontWeight:"lighter", fontSize:"24px"}}>
                                        Criamos a sua primeira Coleção!
                                    </span>
                                    <p style={{fontFamily:"Roboto", fontSize:"16px", margin:"10px 0 0", fontWeight : "normal"}}>
                                        Adicione nela recursos que você queira acessar mais tarde.
                                        <br/>
                                        Crie novas coleções clicando no cartão roxo "Criar Colecão".
                                    </p>
                                </div>
                            }
                            sliceArr={userCollectionsSlice}
                            showMore={showMoreUserCollections}
                            showAll={showAllUserCollections}
                            followed={false}
                        />

                        <PanelTemplateColecao
                            title={"Coleções que eu sigo"}
                            length={followedCollections.length}
                            noContentText={"Você ainda não segue nenhuma coleção."}
                            sliceArr={followedCollectionsSlice}
                            showMore={showMoreFollowedCollections}
                            showAll={showAllFollowedCollections}
                            followed={true}
                        />
                    </React.Fragment>
                ]
            )
        }
        </>
    )
}

function Tentativa (props) {

    return (
        <WhiteContainer>
            <Title
                title={props.title}
                length={props.length}
            />

            <StyledGrid container spacing={1} style={{paddingLeft : "30px", paddingRight : "15px"}}>
                <Grid item md={3} xs={12}>
                    <CardDiv>
                        <div style={{backgroundColor:"#673ab7", height:"250px", display:"flex", justifyContent:"center", alignItems:"center"}}>
                            <CreateNewFolderIcon style={{color:"#fff", fontSize:"70px"}}/>
                            <p style={{fontSize:"16px", margin:"0 0 10px", color : "#fff"}}>
                                CRIAR COLEÇÃO
                            </p>
                        </div>
                    </CardDiv>
                </Grid>

                {
                    props.length === 0 ?
                    (
                        [
                            <Grid item lg={6} md={4} sm={6} xs={12}>
                                <NoContent text={props.noContentText}/>
                            </Grid>
                        ]
                    )
                    :
                    (
                        [
                            <React.Fragment>
                            {
                                props.sliceArr.map( (card) =>
                                <Grid item md={3} xs={12} key={card.id}>
                                    <CollectionCardFunction
                                          name={card.name}
                                          rating={card.score}
                                          type={card.object_type}
                                          description={card.description}
                                          author={card.owner.name}
                                          avatar={card.owner.avatar}
                                          thumbnails={card.items_thumbnails}
                                          likeCount={card.likes_count}
                                          liked={card.liked}
                                          followed={card.followed}
                                          tags={card.tags}
                                      />
                                </Grid>
                                )
                            }
                            </React.Fragment>
                        ]
                    )
                }
                </StyledGrid>
                {
                    props.length  > 0 &&
                    <ButtonsAreaColecao
                        sliceLength={props.sliceArr.length}
                        length={props.length}
                        showMore={() => props.showMore()}
                        showAll={() => props.showAll()}
                    />
                }
        </WhiteContainer>
    )
}

const CardDiv = styled.div`
    margin-top : 10px;
    margin-bottom : 10px;
    width : 95%;
    float : left;
`