import { Controller } from '@hotwired/stimulus';
import { trans, CREATED } from '../translator.js';
import { setLocale } from '@symfony/ux-translator';

/*
 * This is an example Stimulus controller!
 *
 * Any element with a data-controller="hello" attribute will cause
 * this controller to be executed. The name "hello" comes from the filename:
 * hello_controller.js -> "hello"
 *
 * Delete this file or adapt it for your use!
 */
export default class extends Controller {
    
    static values = {
        baseUrlApi: String,
        locale: String,
        apiListParams: String,
        apiResult: Object,
        listCol: String,
        template: String,
        infiniteScroll: String,
        urlDetail: String,
        slug: String,
        urlIndex: String,
    }
    static targets = ['default', 'nbResult', 'entityCreatedAt', 'entityName', 'entityDescription', 'categoryName', 'loader', 'page', 'entityIndexCategoryUrl', 'categoryName']
    
    connect()
    {
        setLocale(this.localeValue);
        
        if( this.element.classList.contains('lock_news') )
        {
            return;
        }
        this.element.classList.add('lock_news');
        
        if( this.hasTemplateValue && this.templateValue == 'detail' )
        {
            this.detail();
        }
        else if( this.hasDefaultTarget )
        {
            this.list();
        }
    }

    list()
    {        
        fetch(this.baseUrlApiValue+'/'+this.localeValue+'/api/news?'+this.apiListParamsValue)
            .then(response => response.json())
            .then((data) => {
                let result = '';
                data.list.forEach((e) => {
                    result += this.getTemplate(e);
                });
                
                this.apiResultValue = data;
                
                this.defaultTarget.innerHTML = result;
                
                if( this.hasNbResultTarget )
                {
                    this.nbResultTargets.forEach((e) => {
                        e.innerHTML = data.nbResults;
                    });                    
                }
                
                if( !this.apiResultValue.nextPageUri )
                {
                    let footer = document.querySelector('#displayFooter');
                    if( footer )
                    {
                        footer.classList.remove('d-none');
                    }
                }
            })
            .catch(error => console.log("Erreur : " + error))
        ;
    }
    
    detail()
    {
        fetch(this.baseUrlApiValue+'/'+this.localeValue+'/api/news/'+this.slugValue)
            .then(response => response.json())
            .then((data) => {
                this.entityNameTarget.innerHTML = data.name;
                
                let createdAt = new Date(data.created);
                this.entityCreatedAtTarget.innerHTML = createdAt.toLocaleDateString();
                this.entityDescriptionTarget.innerHTML = data.description.replace('<img', '<img class="img-fluid"').replace('<a ', '<a target="_blank" rel="nofollow"');
                this.entityIndexCategoryUrlTarget.setAttribute('href', this.urlIndexValue+'?newsCategoryId[]='+data.newsCategory.id);
                
                this.categoryNameTargets.forEach((e) => {
                    e.innerHTML = data.newsCategory.name;
                });
                
                this.loaderTarget.classList.add('d-none');
                this.pageTarget.classList.remove('d-none');
                
                this.apiListParamsValue = 'maxPerPage=3&newsCategoryId='+data.newsCategory.id;
                this.list();
            })
            .catch(error => console.log("Erreur : " + error))
        ;
    }
    
    infiniteScroll()
    {
        if( !this.lockFetchValue && this.apiResultValue.nextPageUri && (window.scrollY + window.innerHeight >= this.defaultTarget.offsetHeight) )
        {
            this.lockFetchValue = true;  
            fetch(this.apiResultValue.nextPageUri)
                .then(response => response.json())
                .then((data) => {
                    let result = this.defaultTarget.innerHTML;
                    data.list.forEach((e) => {
                        result += this.getTemplate(e);
                    });
                    
                    this.defaultTarget.innerHTML = result;
                    this.apiResultValue = data;
                    
                    this.lockFetchValue = false;
                })
                .catch(error => console.log("Erreur : " + error))
            ;
        }
        else if( !this.apiResultValue.nextPageUri )
        {
            let footer = document.querySelector('#displayFooter');
            if( footer )
            {
                footer.classList.remove('d-none')
            }
        }
    }
    
    getTemplate(entity)
    {
        let created = new Date(entity.created);
        let result = `
            <div class="${(this.hasListColValue ? this.listColValue : 'col-md')}">
                <a href="${this.urlDetailValue.replace('slug', entity.slug)}" class="link-underline link-underline-opacity-0">
                    <div class="card rounded border-0 p-3 rounded shadow-none hover-translate-y-n3 card-fluid h-100" :class="{'bg-white': (backgroundColorCard === undefined), 'bg-light': (backgroundColorCard === 'bg-light')}">
                        <img src="${entity.image ? entity.image.uriMedium : 'https://picsum.photos/512/370?blur=10'}" class="card-img-top" alt="${entity.name}" />
                        <div class="text-end d-inline-block mt-n12 pe-2">
                            <i class="fa-solid fa-circle-chevron-right fa-2xl text-primary-aa pe-2"></i>
                        </div>
                        <div class="card-body row">
                            <div class="col-6">
                                <p class="card-text fw-lighter text-muted small">
                                    ${trans(CREATED)} ${created.getDate().toString().padStart(2, "0")}/${(created.getMonth()+1).toString().padStart(2, "0")}/${created.getFullYear()} |
                                </p>
                            </div>
                            <div class="col-6">
                                <p class="fw-semibold text-muted">
                                    <strong>${entity.newsCategory.name}</strong>
                                </p>
                            </div>
                            <div class="col-12">
                                <h5 class="card-title text-primary-aa">${entity.name}</h5>
                                <p class="card-text fw-light">
                                    ${entity.descriptionShort}
                                </p>
                            </div>
                        </div>
                    </div>
                </a>
            </div>
        `;
        
        return result;
    }
}
