import {Injectable} from '@angular/core';

import {Observable} from 'rxjs';

import {
    Application,
    ApplicationEditService,
    ApplicationReadService,
    Item,
    SearchService,
    StartPageConfigReadService,
    Transaction,
    TransactionReadService,
    TreeClassifier
} from 'm2-core';


@Injectable({
    providedIn: 'root'
})
export class CdHelperService {

    constructor(
        private searchService: SearchService,
        private startPageConfigReadService: StartPageConfigReadService,
        private applicationReadService: ApplicationReadService,
        private applicationEditService: ApplicationEditService,
        private transactionReadService: TransactionReadService
    ) {
    }

    /***** Node *****/
    public async getAnyNodeId(): Promise<number> {
        const nodes = await this.searchService.findNodes('1');
        return nodes.keys().next().value;
    }

    public async getNodeIdWithRelations(): Promise<number> {
        return this.getAnyNodeId(); // TODO getNodeIdWithRelations()
    }


    /***** Item *****/
    public async getAnyItem(): Promise<Item> {
        const items = await this.searchService.findItems('1', 0, 1);
        return items[0]?.item;
    }

    public async getAnyItemId(): Promise<number> {
        return (await this.getAnyItem())?.id;
    }


    /***** Classifier *****/
    public async getAnyClassifierId(): Promise<number> {
        const classifiers = (await this.startPageConfigReadService.getAllVisibleEntries())
            .filter(e => e instanceof TreeClassifier);
        const classifier = classifiers.find(c => c.displayName?.includes('ОКВЭД2')) || classifiers[0];
        return classifier?.id;
    }


    /***** Transaction *****/
    public async getAnyTxWithChanges(): Promise<Transaction> {
        const transactions = await this.transactionReadService.findTransactions().toPromise();
        return transactions.find(t => t.hasChanges);
    }


    /***** Application *****/
    public async getAnyApplication(): Promise<Application> {
        const tx = (await this.transactionReadService.findTransactions().toPromise())
            .find(t => t.relatedApplication > 0);
        return this.applicationReadService.getApplicationById(tx.relatedApplication, true);
    }

    public getNextApplicationGroupUid(): Observable<string> {
        return this.applicationEditService.createApplicationGroup();
    }

}
