import { __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import gql from 'graphql-tag';
import { css, html, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';
import { consume } from '@lit/context';
import { i18next } from '@operato/i18n';
import { ScrollbarStyles } from '@operato/styles';
import { client } from '@operato/graphql';
import { OxUserPreferencesContext } from '@operato/p13n';
import '@operato/mini-map/ox-zoomable-image.js';
import { SMALLVALUE, convertByUserUnit, formatValueWithPrecision, changeStreamTypeString } from './utils';
var STED_COMPOSITION_LIST = ['H2O', 'N2', 'O2', 'N2O', 'CO2', 'CH4', 'C2H6', 'C3H8', 'C4H10', 'C5H12'];
let ProcessReport = class ProcessReport extends LitElement {
    constructor() {
        super(...arguments);
        this.userPreferenceKey = 'user-units';
        this.userPreference = null;
    }
    async connectedCallback() {
        super.connectedCallback();
        this.userPreference = await this.contextUserPreferences.get(this.userPreferenceKey);
    }
    // Function to handle the download button click
    async handleDownload() {
        var _a;
        const processId = (_a = this.process) === null || _a === void 0 ? void 0 : _a.id;
        if (!processId) {
            console.error('Process ID is missing');
            return;
        }
        try {
            var response = await client.query({
                query: gql `
          query DownloadLevel1AnalysisReport($id: String!) {
            downloadLevel1AnalysisReport(id: $id)
          }
        `,
                variables: { id: processId }
            });
            const downloadUrl = response.data.downloadLevel1AnalysisReport;
            if (downloadUrl) {
                const link = document.createElement('a');
                link.href = downloadUrl;
                link.download = `STED-L1-${this.process.name}.pdf`;
                link.click();
            }
            else {
                console.error('Failed to retrieve the download URL');
            }
        }
        catch (error) {
            console.error('Error while downloading the report:', error);
        }
    }
    render() {
        var _a, _b, _c, _d;
        var process = this.process || { name: '' };
        var stedNodes = (this.stedNodes || []);
        var smartGuides = (this.smartGuides || []);
        var stedModuleList = [];
        var massFractions = [];
        var moleFractions = [];
        stedNodes.forEach(stedNode => {
            let nodeName = `${stedNode.type}(${stedNode.name})`;
            stedNode.inlets.map(inlet => {
                var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
                !stedModuleList.some(sm => sm.name === inlet.name) &&
                    stedModuleList.push({
                        name: inlet.name,
                        kind: inlet.kind,
                        type: inlet.type,
                        T: (_a = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _a === void 0 ? void 0 : _a.T,
                        m: (_b = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _b === void 0 ? void 0 : _b.m,
                        p: (_c = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _c === void 0 ? void 0 : _c.p,
                        h: (_d = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _d === void 0 ? void 0 : _d.h,
                        Y: (_e = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _e === void 0 ? void 0 : _e.Y,
                        X: (_f = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _f === void 0 ? void 0 : _f.X,
                        MC: (_g = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _g === void 0 ? void 0 : _g.MC,
                        specificHeat: (_h = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _h === void 0 ? void 0 : _h.spheat,
                        pwr: (_j = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _j === void 0 ? void 0 : _j.pwr,
                        htr: (_k = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _k === void 0 ? void 0 : _k.htr,
                        material: (_l = inlet === null || inlet === void 0 ? void 0 : inlet.data) === null || _l === void 0 ? void 0 : _l.material
                    });
            });
            stedNode.outlets.map(outlet => {
                var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l;
                !stedModuleList.some(sm => sm.name === outlet.name) &&
                    stedModuleList.push({
                        name: outlet.name,
                        kind: outlet.kind,
                        type: outlet.type,
                        T: (_a = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _a === void 0 ? void 0 : _a.T,
                        m: (_b = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _b === void 0 ? void 0 : _b.m,
                        p: (_c = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _c === void 0 ? void 0 : _c.p,
                        h: (_d = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _d === void 0 ? void 0 : _d.h,
                        Y: (_e = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _e === void 0 ? void 0 : _e.Y,
                        X: (_f = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _f === void 0 ? void 0 : _f.X,
                        MC: (_g = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _g === void 0 ? void 0 : _g.MC,
                        specificHeat: (_h = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _h === void 0 ? void 0 : _h.spheat,
                        pwr: (_j = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _j === void 0 ? void 0 : _j.pwr,
                        htr: (_k = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _k === void 0 ? void 0 : _k.htr,
                        material: (_l = outlet === null || outlet === void 0 ? void 0 : outlet.data) === null || _l === void 0 ? void 0 : _l.material
                    });
            });
        });
        STED_COMPOSITION_LIST.forEach(sc => {
            massFractions.push(stedModuleList.map(sm => (sm.type === 'fluid' ? (sc in sm.Y ? sm.Y[sc] : null) : null)));
            moleFractions.push(stedModuleList.map(sm => (sm.type === 'fluid' ? (sc in sm.X ? sm.X[sc] : null) : null)));
        });
        const smartGuide = smartGuides.map(({ name, guide, type }) => html `<li>(${type}, ${name})${guide}</li>`);
        return html `
      <button id="download-button" @click=${this.handleDownload}><md-icon>download</md-icon>PDF Report</button>

      ${process.diagram
            ? html ` <ox-zoomable-image src=${process.diagram} restrict-boundary></ox-zoomable-image> `
            : html ``}

      <div id="smart-guide">
        <h2><md-icon>auto_stories</md-icon> Smart Guide</h2>
        <p>${smartGuide}</p>
      </div>

      <table>
        <tr>
          <th colspan="2">구분</th>
          ${stedModuleList.map(sm => html ` <th>${sm.name}</th> `)}
        </tr>
        <tr>
          <td subTh colspan="2">${i18next.t('label.type')}</td>
          ${stedModuleList.map(sm => html ` <td>${changeStreamTypeString(sm.type)}</td> `)}
        </tr>
        <tr>
          <td subTh colspan="2">
            ${i18next.t('label.mass-fraction')} (${((_a = this.userPreference) === null || _a === void 0 ? void 0 : _a['kg/sec']) || 'kg/sec'})
          </td>
          ${stedModuleList.map(sm => {
            var _a;
            return html `
                <td>${formatValueWithPrecision(convertByUserUnit(sm.m, 'kg/sec', (_a = this.userPreference) === null || _a === void 0 ? void 0 : _a['kg/sec']))}</td>
              `;
        })}
        </tr>
        <tr>
          <td subTh colspan="2">${i18next.t('label.temperature')} (${((_b = this.userPreference) === null || _b === void 0 ? void 0 : _b['K']) || 'K'})</td>
          ${stedModuleList.map(sm => { var _a; return html ` <td>${formatValueWithPrecision(convertByUserUnit(sm.T, 'K', (_a = this.userPreference) === null || _a === void 0 ? void 0 : _a['K']))}</td> `; })}
        </tr>
        <tr>
          <td subTh colspan="2">${i18next.t('label.pressure')} (${((_c = this.userPreference) === null || _c === void 0 ? void 0 : _c['Pa']) || 'Pa'})</td>
          ${stedModuleList.map(sm => { var _a; return html ` <td>${formatValueWithPrecision(convertByUserUnit(sm.p, 'Pa', (_a = this.userPreference) === null || _a === void 0 ? void 0 : _a['Pa']))}</td> `; })}
        </tr>
        <tr>
          <td subTh colspan="2">비엔탈피 (${((_d = this.userPreference) === null || _d === void 0 ? void 0 : _d['J/kg']) || 'J/kg'})</td>
          ${stedModuleList.map(sm => {
            var _a;
            return html `
                <td>${formatValueWithPrecision(convertByUserUnit(sm.h, 'J/kg', (_a = this.userPreference) === null || _a === void 0 ? void 0 : _a['J/kg']))}</td>
              `;
        })}
        </tr>
        <tr>
          <td subTh colspan="2">${i18next.t('label.moisture-content')} (%)</td>
          ${stedModuleList.map(sm => html ` <td>${formatValueWithPrecision(sm.MC)}</td> `)}
        </tr>
        <tr>
          <td subTh colspan="2">${i18next.t('label.solid-material')}</td>
          ${stedModuleList.map(sm => html ` <td>${sm.material || '-'}</td> `)}
        </tr>

        ${massFractions.map((subs, idx) => {
            return html `
            <tr formation>
              ${idx == 0
                ? html ` <td subTh2 rowspan="${massFractions.length}">${i18next.t('label.mass-fraction')}</td> `
                : html ``}
              ${(subs && subs.reduce((acc, cur) => acc + parseFloat(cur || 0.0), 0.0)) > SMALLVALUE
                ? html `
                    <td>${STED_COMPOSITION_LIST[idx]}</td>
                    ${subs.map(sub => html ` <td>${formatValueWithPrecision(sub || 0.0)}</td>`)}
                  `
                : html ``}
            </tr>
          `;
        })}
        ${moleFractions.map((subs, idx) => {
            return html `
            <tr formation>
              ${idx == 0
                ? html ` <td subTh2 rowspan="${moleFractions.length}">${i18next.t('label.mole-fraction')}</td> `
                : html ``}
              ${(subs && subs.reduce((acc, cur) => acc + parseFloat(cur || 0.0), 0.0)) > SMALLVALUE
                ? html `
                    <td>${STED_COMPOSITION_LIST[idx]}</td>
                    ${subs.map(sub => html ` <td>${formatValueWithPrecision(sub || 0.0)}</td>`)}
                  `
                : html ``}
            </tr>
          `;
        })}
      </table>
    `;
    }
    close() {
        history.back();
    }
};
ProcessReport.styles = [
    ScrollbarStyles,
    css `
      :host {
        display: grid;
        grid-template-columns: 1.5fr 1fr;
        grid-template-rows: min-content;
        align-content: baseline;
        background-color: var(--main-section-background-color);
        overflow: auto;
        position: relative;
      }

      #download-button {
        position: absolute;
        top: var(--spacing-medium);
        right: var(--spacing-medium);
        color: var(--md-sys-color-on-primary);
        background-color: var(--md-sys-color-primary);
        border: none;
        padding: var(--spacing-small) var(--spacing-medium);
        cursor: pointer;
        font-size: 0.9em;
        border-radius: 4px;
        display: flex;
        align-items: center;
        gap: var(--spacing-medium);
      }

      #download-button:hover {
        color: var(--md-sys-color-on-secondary);
        background-color: var(--md-sys-color-secondary);
      }

      ox-zoomable-image {
        display: block;
        min-height: 300px;
        max-width: 100%;
        max-height: 100%;
        border: var(--border-dark-color);
      }

      ox-process-viewer {
        display: block;
        min-height: 300px;
        max-height: 100%;
        border: var(--border-dark-color);
      }

      h2 {
        margin: 0;
        padding: var(--spacing-small) 4px;
        vertical-align: middle;
        font: var(--subtitle-font);
        color: var(--subtitle-text-color);
        text-transform: capitalize;
      }
      h2 md-icon {
        --md-icon-size: 1.1em;
        position: relative;
        top: 3px;
      }
      #smart-guide {
        padding: var(--spacing-medium);
        border-left: 1px dashed rgba(0, 0, 0, 0.15);
      }
      table {
        grid-column: 1 / span 2;
        border-collapse: collapse;
        background-color: #fff;
        width: 100%;
        margin: auto;
      }
      tr {
        border-bottom: var(--border-dark-color);
      }
      th {
        border-top: 2px solid var(--focus-background-color);
        border-right: 1px solid var(--primary-color);
        background-color: var(--secondary-text-color);
        padding: var(--spacing-small);
        color: var(--theme-white-color);
      }

      tr td:first-child {
        background-color: rgba(0, 0, 0, 0.05);
        text-align: right;
      }
      td {
        padding: var(--spacing-small);
        border-right: var(--border-dark-color);
        text-align: right;
        font-size: 0.8em;
      }
      td:last-child {
        border-right: 0;
      }

      tr[doubleline] {
        border-bottom: 2px double rgba(0, 0, 0, 0.2);
      }

      [subTh] {
        text-align: center !important;
        font-weight: bold;
      }

      [subTh2] {
        background-color: rgba(var(--primary-color-rgb), 0.5) !important;
        color: #fff;
        text-align: center !important;
        font-weight: bold;
        font-size: 1em;
      }
      [formation] td:first-child {
        background-color: rgba(var(--primary-color-rgb), 0.05) !important;
        font-weight: bold;
        color: var(--primary-color);
      }
      [formation]:nth-child(odd) {
        background-color: rgba(var(--primary-color-rgb), 0.02);
      }

      tr:hover,
      [formation]:hover {
        background-color: var(--focus-background-color) !important;
      }

      @media screen and (max-width: 460px) {
        :host {
          width: 100vw;
          display: block;
        }
        #smart-guide {
          padding: 0 var(--spacing-medium) var(--spacing-medium) var(--spacing-medium);
        }
        p {
          margin: 0;
        }
      }
    `
];
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], ProcessReport.prototype, "process", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], ProcessReport.prototype, "evaluation", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], ProcessReport.prototype, "stedNodes", void 0);
__decorate([
    property({ type: Array }),
    __metadata("design:type", Array)
], ProcessReport.prototype, "smartGuides", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", Object)
], ProcessReport.prototype, "userPreferenceKey", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], ProcessReport.prototype, "userPreference", void 0);
__decorate([
    consume({ context: OxUserPreferencesContext, subscribe: true }),
    __metadata("design:type", Map)
], ProcessReport.prototype, "contextUserPreferences", void 0);
ProcessReport = __decorate([
    customElement('process-report')
], ProcessReport);
export { ProcessReport };
//# sourceMappingURL=process-report.js.map