import {Component, ElementRef} from '@angular/core';
import {ActivatedRoute} from '@angular/router';

import {switchMap, tap} from 'rxjs/operators';

import {DOMUtils} from 'm2-core';
import {CD_ROUTING} from '../../../config';
import {CdCodeExampleService} from './service/cd-code-example.service';
import {CdContentComponent} from '../abstract/CdContentComponent';


@Component({
    template: `
        <section *ngFor="let snippet of codeSnippets$ | async"
                 #sectionRef
                 id="{{snippet.fragment}}"
                 class="cd-content-section"
        >
            <h4 *ngIf="snippet.header">{{snippet.header}}</h4>
            <cd-code [langCode]="snippet.langCode || 'ts'">{{snippet.code}}</cd-code>
        </section>
    `
})
export class CdCodeExampleComponent extends CdContentComponent {

    constructor(
        private elementRef: ElementRef<HTMLElement>,
        protected activatedRoute: ActivatedRoute,
        private cdCodeExampleService: CdCodeExampleService
    ) {
        super();
    }

    codeSnippets$ = this.activatedRoute.params
        .pipe(
            switchMap(params => this.cdCodeExampleService.getCodeExample(params[CD_ROUTING.PARAMS.SECTION])),
            // tap(snippets => console.log(snippets.length))
            // tap(() => {
            //     const scrollContainer = DOMUtils.getClosestParent(this.elementRef.nativeElement,
            //             e => window.getComputedStyle(e).overflowY.startsWith('auto'));
            //     if (scrollContainer) {
            //         // scroll top when section changes
            //         scrollContainer.scrollTop = 0;
            //     }
            // })
        );

}
