import {AfterViewInit, Component, TemplateRef, ViewChild} from '@angular/core';

import {from, merge, Observable, Subject} from 'rxjs';
import {map, switchMap, tap} from 'rxjs/operators';

import {
    CardRow,
    ClassifiableSelectorConfig,
    DataReadService,
    Item,
    ItemValuesService,
    LayerService,
    SelectionTargetType,
    TemplateRow, TransactionService
} from 'm2-core';
import {CdDemoComponent} from '../../../abstract/CdDemoComponent';
import {CdHelperService} from '../../../../../service/cd-helper.service';


@Component({
    template: `
        <section class="cd-content-section">
            <h4 i18n>Атрибуты позиции</h4>

            <p>
                Модель карточки позиции может быть построена из произвольной комбинации экземпляром классов <code cdApiLink="/miscellaneous/typealiases.html#ItemCardRow">ItemCardRow</code>.  
            </p>
            
            <div class="cd-demo-widget sdi-card-wrapper">
                <card-rows
                        *ngIf="cardData$ | async as cardData"
                        [editModeON]="editModeON$ | async"
                        [owner]="cardData.item"
                        [rootRows]="cardData.rows"
                        [loadingData]="loading"
                >
                </card-rows>
                
                <!-- region itemSelectorRowTmpl -->
                <!-- Custom card row template example -->
                <ng-template #itemSelectorRowTmpl let-cardRow>
                    <tr class="card-row">
                        <td left-card-col [level]="cardRow.level" i18n>
                            Выбранная позиция
                        </td>
                        <td right-card-col>
                            <div class="cell-content-wrapper">
                                <div class="overflow-ellipsis">
                                    <classifiable
                                            [classifiableElement]="cardRow.params"
                                            target="_blank"
                                            [showHintCard]="true"
                                            [showStatus]="true"
                                            [showIcon]="false"
                                    >
                                    </classifiable>
                                </div>
                                <div class="cell-tools">
                                    <button class="sdi-btn sdi-btn_icon" 
                                            i18n-title="@@selectItemTitle" title="Выбрать позицию"
                                            (click)="onSelectItemClick()"
                                    >
                                        <i class="fa fa-folder-open"></i>
                                    </button>
                                </div>
                            </div>
                        </td>
                    </tr>
                </ng-template>
                <!-- endregion itemSelectorRowTmpl -->
            </div>
        </section>
    `
})
export class CdItemCardRowDemoComponent extends CdDemoComponent implements AfterViewInit {

    constructor(
        private cdHelperService: CdHelperService,
        private itemValuesService: ItemValuesService,
        private dataReadService: DataReadService,
        private layerService: LayerService,
        private txService: TransactionService
    ) {
        super();
    }

    @ViewChild('itemSelectorRowTmpl') itemSelectorRowTmpl: TemplateRef<any>;


    selectedItemSubj$ = new Subject<number>();

    loading?: boolean;
    cardData$?: Observable<{ item: Item, rows: CardRow[] }>;

    editModeON$ = this.txService.editModeON$;


    ngAfterViewInit() {
        this.cardData$ = merge(
            from(this.cdHelperService.getAnyItem()),
            from(this.selectedItemSubj$.pipe(switchMap(id => this.dataReadService.getElementById<Item>(id))))
        ).pipe(
            tap(() => this.loading = true),
            switchMap(item => from(this.itemValuesService.getItemValuesRows(item, null, { summaryRow: { showParentNodeImage: true } }))
                .pipe(
                    map(valueRows => {
                        const rows = [
                            // custom card row example
                            new TemplateRow(null, this.itemSelectorRowTmpl, item),
                            // summary rows (status, parent node image, etc.) + value rows
                            ...valueRows
                        ];
                        return { item, rows };
                    })
                )
            ),
            tap(() => this.loading = false)
        );
    }


    onSelectItemClick(): void {
        const config = new ClassifiableSelectorConfig(SelectionTargetType.ITEM);
        config.handler = itemIds => this.selectedItemSubj$.next(itemIds[0]);
        this.layerService.activateSelector(config);
    }

}
