import '@material/web/icon/icon.js'

import { css, html, LitElement } from 'lit'
import { customElement, property } from 'lit/decorators.js'

import { i18next } from '@operato/i18n'
import { ScrollbarStyles } from '@operato/styles'

import { SMALLVALUE, formatValueWithPrecision, changeStreamTypeString } from './utils'

// TODO: check if this is the correct list
var STED_COMPOSITION_LIST = ['H2O', 'N2', 'O2', 'N2O', 'CO2', 'CH4', 'C2H6', 'C3H8']

@customElement('process-report')
export class ProcessReport extends LitElement {
  static 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;
      }

      img {
        display: block;

        margin: var(--margin-default) auto;
        max-width: 100%;
        max-height: 100%;
        border: var(--border-dark-color);
      }
      h2 {
        margin: 0;
        padding: var(--padding-narrow) 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(--padding-wide);
        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(--padding-narrow);
        color: var(--theme-white-color);
      }

      tr td:first-child {
        background-color: rgba(0, 0, 0, 0.05);
        text-align: right;
      }
      td {
        padding: var(--padding-narrow);
        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(--padding-default) var(--padding-default) var(--padding-default);
        }
        p {
          margin: 0;
        }
      }
    `
  ]

  @property({ type: Object }) process: any
  @property({ type: Object }) evaluation: any
  @property({ type: Object }) stedNodes: any
  @property({ type: Array }) smartGuides?: { type: string; name: string; guide: string }[]

  render() {
    var process = this.process || { name: '' }
    var stedNodes = (this.stedNodes || []) as any[]
    var smartGuides = (this.smartGuides || []) as any[]
    var stedModuleList = [] as any[]
    var massFractions: any[] = []
    var moleFractions: any[] = []

    stedNodes.forEach(stedNode => {
      let nodeName = `${stedNode.type}(${stedNode.name})`
      stedNode.inlets.map(inlet => {
        !stedModuleList.some(sm => sm.name === inlet.name) &&
          stedModuleList.push({
            name: inlet.name,
            kind: inlet.kind,
            type: inlet.type,
            T: inlet?.data?.T,
            m: inlet?.data?.m,
            p: inlet?.data?.p,
            h: inlet?.data?.h,
            Y: inlet?.data?.Y,
            X: inlet?.data?.X,
            MC: inlet?.data?.MC,
            specificHeat: inlet?.data?.spheat,
            pwr: inlet?.data?.pwr,
            htr: inlet?.data?.htr,
            material: inlet?.data?.material
          })
      })
      stedNode.outlets.map(outlet => {
        !stedModuleList.some(sm => sm.name === outlet.name) &&
          stedModuleList.push({
            name: outlet.name,
            kind: outlet.kind,
            type: outlet.type,
            T: outlet?.data?.T,
            m: outlet?.data?.m,
            p: outlet?.data?.p,
            h: outlet?.data?.h,
            Y: outlet?.data?.Y,
            X: outlet?.data?.X,
            MC: outlet?.data?.MC,
            specificHeat: outlet?.data?.spheat,
            pwr: outlet?.data?.pwr,
            htr: outlet?.data?.htr,
            material: outlet?.data?.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(({ guide }) => guide).join('</br>')

    return html`
      ${process.thumbnail ? html` <img src=${process.thumbnail} /> ` : 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')} (kg/sec)</td>
          ${stedModuleList.map(sm => html` <td>${formatValueWithPrecision(sm.m)}</td> `)}
        </tr>
        <tr>
          <td subTh colspan="2">${i18next.t('label.temperature')} (K)</td>
          ${stedModuleList.map(sm => html` <td>${formatValueWithPrecision(sm.T)}</td> `)}
        </tr>
        <tr>
          <td subTh colspan="2">${i18next.t('label.pressure')} (Pa)</td>
          ${stedModuleList.map(sm => html` <td>${formatValueWithPrecision(sm.p)}</td> `)}
        </tr>
        <tr>
          <td subTh colspan="2">비엔탈피 (J/kg)</td>
          ${stedModuleList.map(sm => html` <td>${formatValueWithPrecision(sm.h)}</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()
  }
}
