var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { Component, Input, Output, EventEmitter } from '@angular/core';
import { DisplayMode, Jurisdiction, CaseType, CaseState, SearchResultView, CaseField, DRAFT_PREFIX, PaginationMetadata, SortParameters, SortOrder } from '../../domain';
import { FormGroup } from '@angular/forms';
import { ActivityService, SearchResultViewItemComparatorFactory } from '../../services';
import { CaseReferencePipe } from '../../pipes';
import { AbstractAppConfig } from '../../../app.config';
import { PlaceholderService } from '../../directives';
var SearchResultComponent = /** @class */ (function () {
    function SearchResultComponent(searchResultViewItemComparatorFactory, appConfig, activityService, caseReferencePipe, placeholderService) {
        this.activityService = activityService;
        this.caseReferencePipe = caseReferencePipe;
        this.placeholderService = placeholderService;
        this.ICON = DisplayMode.ICON;
        this.changePage = new EventEmitter();
        this.selected = {};
        this.searchResultViewItemComparatorFactory = searchResultViewItemComparatorFactory;
        this.paginationPageSize = appConfig.getPaginationPageSize();
        this.hideRows = false;
    }
    SearchResultComponent_1 = SearchResultComponent;
    SearchResultComponent.prototype.ngOnChanges = function (changes) {
        if (changes['resultView']) {
            this.hideRows = false;
            this.sortParameters = undefined;
            // Clone `resultView` to prevent sorting the external variable
            this.resultView = {
                columns: this.resultView.columns.slice(0),
                results: this.resultView.results.slice(0),
                hasDrafts: this.resultView.hasDrafts
            };
            this.resultView.columns = this.resultView.columns.sort(function (a, b) {
                return a.order - b.order;
            });
            this.hydrateResultView();
            this.draftsCount = this.draftsCount ? this.draftsCount : this.numberOfDrafts();
        }
        if (changes['page']) {
            this.selected.page = (changes['page']).currentValue;
        }
    };
    /**
     * Hydrates result view with case field definitions.
     */
    // A longer term resolution is to move this piece of logic to the backend
    SearchResultComponent.prototype.hydrateResultView = function () {
        var _this = this;
        this.resultView.results.forEach(function (result) {
            var caseFields = [];
            Object.keys(result.case_fields).forEach(function (fieldId) {
                var field = result.case_fields[fieldId];
                caseFields.push(Object.assign(new CaseField(), {
                    id: fieldId,
                    label: null,
                    field_type: {},
                    value: field,
                    display_context: null,
                }));
            });
            result.hydrated_case_fields = caseFields;
            result.columns = {};
            _this.resultView.columns.forEach(function (col) {
                result.columns[col.case_field_id] = _this.buildCaseField(col, result);
            });
        });
    };
    SearchResultComponent.prototype.goToPage = function (page) {
        this.hideRows = true;
        this.selected.init = false;
        this.selected.jurisdiction = this.jurisdiction;
        this.selected.caseType = this.caseType;
        this.selected.caseState = this.caseState;
        this.selected.formGroup = this.caseFilterFG;
        this.selected.metadataFields = this.metadataFields;
        this.selected.page = page;
        // Apply filters
        var queryParams = {};
        queryParams[SearchResultComponent_1.PARAM_JURISDICTION] = this.selected.jurisdiction ? this.selected.jurisdiction.id : null;
        queryParams[SearchResultComponent_1.PARAM_CASE_TYPE] = this.selected.caseType ? this.selected.caseType.id : null;
        queryParams[SearchResultComponent_1.PARAM_CASE_STATE] = this.selected.caseState ? this.selected.caseState.id : null;
        this.changePage.emit({
            selected: this.selected,
            queryParams: queryParams
        });
    };
    SearchResultComponent.prototype.buildCaseField = function (col, result) {
        return Object.assign(new CaseField(), {
            id: col.case_field_id,
            label: col.label,
            field_type: col.case_field_type,
            value: result.case_fields[col.case_field_id],
            display_context: null,
        });
    };
    SearchResultComponent.prototype.getColumnsWithPrefix = function (col, result) {
        col.value = this.draftPrefixOrGet(col, result);
        col.value = this.placeholderService.resolvePlaceholders(result.case_fields, col.value);
        return col;
    };
    SearchResultComponent.prototype.hasResults = function () {
        var _a, _b, _c;
        return ((_b = (_a = this.resultView) === null || _a === void 0 ? void 0 : _a.results) === null || _b === void 0 ? void 0 : _b.length) && ((_c = this.paginationMetadata) === null || _c === void 0 ? void 0 : _c.total_pages_count);
    };
    SearchResultComponent.prototype.hasDrafts = function () {
        var _a;
        return (_a = this.resultView) === null || _a === void 0 ? void 0 : _a.hasDrafts();
    };
    SearchResultComponent.prototype.comparator = function (column) {
        return this.searchResultViewItemComparatorFactory.createSearchResultViewItemComparator(column);
    };
    SearchResultComponent.prototype.sort = function (column) {
        if (this.comparator(column) === undefined) {
            return;
        }
        else if (this.isSortAscending(column)) {
            this.sortParameters = new SortParameters(this.comparator(column), SortOrder.ASCENDING);
        }
        else {
            this.sortParameters = new SortParameters(this.comparator(column), SortOrder.DESCENDING);
        }
    };
    SearchResultComponent.prototype.sortWidget = function (column) {
        return this.isSortAscending(column) ? '&#9660;' : '&#9650;';
    };
    SearchResultComponent.prototype.activityEnabled = function () {
        return this.activityService.isEnabled;
    };
    SearchResultComponent.prototype.hyphenateIfCaseReferenceOrGet = function (col, result) {
        if (col.case_field_id === '[CASE_REFERENCE]') {
            return this.caseReferencePipe.transform(result.case_fields[col.case_field_id]);
        }
        else {
            if (col.id) {
                if (col.id === '[CASE_REFERENCE]') {
                    return this.caseReferencePipe.transform(result.case_fields[col.id]);
                }
                else {
                    return result.case_fields[col.id];
                }
            }
            else {
                return result.case_fields[col.case_field_id];
            }
        }
    };
    SearchResultComponent.prototype.draftPrefixOrGet = function (col, result) {
        return result.case_id.startsWith(DRAFT_PREFIX) ? DRAFT_PREFIX : this.hyphenateIfCaseReferenceOrGet(col, result);
    };
    SearchResultComponent.prototype.isSortAscending = function (column) {
        var currentSortOrder = this.currentSortOrder(column);
        return currentSortOrder === SortOrder.UNSORTED || currentSortOrder === SortOrder.DESCENDING;
    };
    SearchResultComponent.prototype.currentSortOrder = function (column) {
        var isAscending = true;
        var isDescending = true;
        if (this.comparator(column) === undefined) {
            return SortOrder.UNSORTED;
        }
        for (var i = 0; i < this.resultView.results.length - 1; i++) {
            var comparison = this.comparator(column).compare(this.resultView.results[i], this.resultView.results[i + 1]);
            isDescending = isDescending && comparison <= 0;
            isAscending = isAscending && comparison >= 0;
            if (!isAscending && !isDescending) {
                break;
            }
        }
        return isAscending ? SortOrder.ASCENDING : isDescending ? SortOrder.DESCENDING : SortOrder.UNSORTED;
    };
    SearchResultComponent.prototype.getFirstResult = function () {
        var currentPage = (this.selected.page ? this.selected.page : 1);
        return ((currentPage - 1) * this.paginationPageSize) + 1 + this.getDraftsCountIfNotPageOne(currentPage);
    };
    SearchResultComponent.prototype.getLastResult = function () {
        var currentPage = (this.selected.page ? this.selected.page : 1);
        return ((currentPage - 1) * this.paginationPageSize) + this.resultView.results.length + this.getDraftsCountIfNotPageOne(currentPage);
    };
    SearchResultComponent.prototype.getTotalResults = function () {
        return this.paginationMetadata.total_results_count + this.draftsCount;
    };
    SearchResultComponent.prototype.getDraftsCountIfNotPageOne = function (currentPage) {
        return currentPage > 1 ? this.draftsCount : 0;
    };
    SearchResultComponent.prototype.numberOfDrafts = function () {
        return this.resultView.results.filter(function (_) { return _.case_id.startsWith(DRAFT_PREFIX); }).length;
    };
    var SearchResultComponent_1;
    SearchResultComponent.PARAM_JURISDICTION = 'jurisdiction';
    SearchResultComponent.PARAM_CASE_TYPE = 'case-type';
    SearchResultComponent.PARAM_CASE_STATE = 'case-state';
    __decorate([
        Input(),
        __metadata("design:type", Jurisdiction)
    ], SearchResultComponent.prototype, "jurisdiction", void 0);
    __decorate([
        Input(),
        __metadata("design:type", CaseType)
    ], SearchResultComponent.prototype, "caseType", void 0);
    __decorate([
        Input(),
        __metadata("design:type", CaseState)
    ], SearchResultComponent.prototype, "caseState", void 0);
    __decorate([
        Input(),
        __metadata("design:type", FormGroup)
    ], SearchResultComponent.prototype, "caseFilterFG", void 0);
    __decorate([
        Input(),
        __metadata("design:type", SearchResultView)
    ], SearchResultComponent.prototype, "resultView", void 0);
    __decorate([
        Input(),
        __metadata("design:type", Number)
    ], SearchResultComponent.prototype, "page", void 0);
    __decorate([
        Input(),
        __metadata("design:type", PaginationMetadata)
    ], SearchResultComponent.prototype, "paginationMetadata", void 0);
    __decorate([
        Input(),
        __metadata("design:type", Array)
    ], SearchResultComponent.prototype, "metadataFields", void 0);
    __decorate([
        Output(),
        __metadata("design:type", EventEmitter)
    ], SearchResultComponent.prototype, "changePage", void 0);
    SearchResultComponent = SearchResultComponent_1 = __decorate([
        Component({
            selector: 'ccd-search-result',
            template: "\n    <table *ngIf=\"hasResults() || hasDrafts()\">\n      <caption>\n        <h2 class=\"heading-h2\">{{ caseState ? 'List' : 'Search result' }}</h2>\n        <div *ngIf=\"(hasResults() || hasDrafts())\" class=\"pagination-top\"\n             attr.aria-label=\"{{ getTotalResults() }} results have been found\">\n          <span class=\"text-16\">Displaying {{ getFirstResult() }} - {{ getLastResult() }} out of {{ getTotalResults() }} results</span>\n        </div>\n      </caption>\n      <thead>\n      <tr>\n        <th *ngFor=\"let col of resultView.columns\">\n          <table class=\"search-result-column-header\"\n                 attr.aria-label=\"Sort by {{col.label}} {{ isSortAscending(col)? 'ascending' : 'descending' }}\">\n            <tbody>\n              <tr>\n                <div class=\"search-result-column-label\" (click)=\"sort(col)\">{{col.label}}</div>\n                <div *ngIf=\"comparator(col)\" class=\"search-result-column-sort\">\n                  <a (click)=\"sort(col)\" class=\"sort-widget\" [innerHTML]=\"sortWidget(col)\" href=\"javascript:void(0)\"></a>\n                </div>\n              </tr>\n            </tbody>\n          </table>\n        </th>\n        <th *ngIf=\"activityEnabled()\" style=\"width: 110px;\"></th>\n      </tr>\n      </thead>\n      <tbody>\n      <tr *ngFor=\"let result of resultView.results | ccdSortSearchResult : sortParameters | paginate: { itemsPerPage: paginationPageSize, currentPage: selected.page, totalItems: paginationMetadata.total_results_count }\">\n\n        <td class=\"search-result-column-cell\" *ngFor=\"let col of resultView.columns; let colIndex = index\">\n\n          <a *ngIf=\"colIndex == 0\" routerLink=\"/case/{{result.case_id}}\"\n             attr.aria-label=\"go to case with Case reference:{{ result.case_id | ccdCaseReference }}\">\n            <ng-container class=\"text-16\" *ngIf=\"!hideRows\">\n              <ccd-field-read *ngIf=\"draftPrefixOrGet(col, result); else case_reference\"\n                              ccdLabelSubstitutor [caseField]=\"getColumnsWithPrefix(result.columns[col.case_field_id], result)\"\n                              [contextFields]=\"result.hydrated_case_fields\"\n                              [elementsToSubstitute]=\"['value']\"></ccd-field-read>\n              <ng-template #case_reference>{{result.case_id | ccdCaseReference}}</ng-template>\n            </ng-container>\n          </a>\n          <div *ngIf=\"colIndex != 0\" class=\"text-16\" [style.visibility]=\"hideRows ? 'hidden' : 'visible'\">\n            <ccd-field-read ccdLabelSubstitutor\n                            [caseField]=\"result.columns[col.case_field_id]\"\n                            [contextFields]=\"result.hydrated_case_fields\"\n                            [elementsToSubstitute]=\"['value']\"></ccd-field-read>\n          </div>\n        </td>\n        <td *ngIf=\"activityEnabled()\">\n          <div [style.visibility]=\"hideRows ? 'hidden' : 'visible'\">\n            <ccd-activity [caseId]=\"result.case_id\" [displayMode]=\"ICON\"></ccd-activity>\n          </div>\n        </td>\n      </tr>\n      </tbody>\n    </table>\n    <pagination-controls [style.visibility]=\"hideRows ? 'hidden' : 'visible'\" *ngIf=\"hasResults()\" class=\"pagination\" (pageChange)=\"goToPage($event)\" autoHide=\"true\" maxSize=\"8\" screenReaderPaginationLabel=\"Pagination\" screenReaderPageLabel=\"page\" screenReaderCurrentLabel=\"You're on page\"></pagination-controls>\n    <div *ngIf=\"!(hasResults() || hasDrafts())\" class=\"notification\"\n         aria-label=\"No records found. Try using different filters.\">\n      No records found. Try using different filters.\n    </div>\n  ",
            styles: ["\n    table thead tr th{vertical-align:top}table tbody tr td{font-size:16px;word-wrap:break-word}table tbody tr td a{color:#005ea5;background-color:#fff}table .caseid-col{white-space:nowrap}.pagination ::ng-deep .ngx-pagination{padding-top:25px;text-decoration:none;text-align:center;font-size:16px}@media (min-width: 769px){.pagination ::ng-deep .ngx-pagination{font-size:16px}}.pagination ::ng-deep .ngx-pagination a{color:#005da6}.pagination ::ng-deep .ngx-pagination .current{background-color:#fff;color:#4C2C92}.pagination ::ng-deep .ngx-pagination .disabled{display:none}.notification{text-align:center;padding:30px 0px 30px 0px;margin-top:75px}a:hover{color:#005ea5}.search-result-column-header{width:unset;table-layout:normal}.search-result-column-header div{display:table-cell;width:auto}@media screen and (max-width: 379px){.search-result-column-header div{display:block;float:right}}.search-result-column-label{font-size:16px;font-weight:bold;word-wrap:break-word;cursor:pointer;padding-right:15px}.search-result-column-sort{font-size:16px}.sort-widget{cursor:pointer;text-decoration:none;color:#231F20}span.heading-medium{margin-top:-20px}\n  "]
        }),
        __metadata("design:paramtypes", [SearchResultViewItemComparatorFactory,
            AbstractAppConfig,
            ActivityService,
            CaseReferencePipe,
            PlaceholderService])
    ], SearchResultComponent);
    return SearchResultComponent;
}());
export { SearchResultComponent };
//# sourceMappingURL=search-result.component.js.map