import {AfterViewInit, Component, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';

import {ClientConfigService, Editor, LayoutConfig} from 'm2-core';
import {NodesTreeComponent} from 'm2-components';
import {CdHelperService} from '../../../../../service/cd-helper.service';


@Component({
    template: `
        <div class="cd-demo-widget h-100" [class.busy-modal]="!isInitialized">
            <sdi-splitter
                    [ratio]="layoutConfig.leftRatio"
                    [showToggle]="true"
                    [isLeftToggle]="false"
                    (resized)="updateConfigRatio($event)"
            >
                <div left-container class="form-section">
                    <div class="form-section__header form-section__header_slim form-section__header_primary">
                        <h4 class="m-0 pt-4 overflow-ellipsis" i18n>Дерево групп</h4>
                    </div>
                    <div class="form-section__body">
                        <nodes-tree
                                [formRouterLinkFn]="formRouterLinkFn"
                        >
                        </nodes-tree>
                    </div>
                </div>

                <div right-container class="form-section">
                    <div class="form-section__header form-section__header_slim">
                        <h4 class="m-0 pt-4 overflow-ellipsis" i18n>Карточка группы</h4>
                    </div>
                    <div class="form-section__body">
                        <router-outlet>
                        </router-outlet>
                    </div>
                </div>
            </sdi-splitter>
        </div>
    `
})
export class CdNodesTreeDemoComponent extends Editor implements AfterViewInit {

    constructor(
        private activatedRoute: ActivatedRoute,
        private router: Router,
        protected clientConfigService: ClientConfigService,
        private cdHelperService: CdHelperService
    ) {
        super();
    }

    @ViewChild(NodesTreeComponent) nodesTreeComponent: NodesTreeComponent;
    

    protected readonly editorId = 'cdNodesTreeDemo';
    layoutConfig: LayoutConfig = { leftRatio: .5 };

    isInitialized = false;

    formRouterLinkFn: NodesTreeComponent['formRouterLinkFn'] = id => `./${id}`;


    ngAfterViewInit(): void {
        this.onTreeInitialized();
    }
    

    async onTreeInitialized() {
        const nodeId = (await this.cdHelperService.getAnyNodeId()) ?? 1;
        await this.nodesTreeComponent.activateNodeById(nodeId);
        await this.router.navigate([`./${nodeId}`], { relativeTo: this.activatedRoute });
        this.isInitialized = true;
    }

}
