import {Component} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {DomSanitizer} from '@angular/platform-browser';

import {combineLatest} from 'rxjs';
import {map} from 'rxjs/operators';

import {EndpointConfigService} from 'm2-core';
import {CD_PLUGIN_DOCUMENTATION_CTX, CD_ROUTING} from '../../../config';
import {getDocsPath} from '../../../content-config';


@Component({
    template: `
        <iframe [src]="src$ | async"
                class="docs-frame"
        >
        </iframe>
    `,
    styles: [`
        .docs-frame {
            width: calc(100% + 58px);
            height: calc(100% + 8px);
            border: 0;
            margin: -1em 0 0 -2em;
        }
    `]
})
export class CdApiOverviewComponent {

    constructor(
        private activatedRoute: ActivatedRoute,
        private sanitizer: DomSanitizer,
        private endpointConfigService: EndpointConfigService
    ) {
    }

    src$ = combineLatest([
        this.activatedRoute.params,
        this.activatedRoute.fragment
    ])
        .pipe(map(([params, fragment]) => {
            const url = this.endpointConfigService.baseUrl
                + CD_PLUGIN_DOCUMENTATION_CTX
                + getDocsPath(params[CD_ROUTING.PARAMS.SECTION], fragment);
            return this.sanitizer.bypassSecurityTrustResourceUrl(url);
        }));

}
