import { __asyncGenerator, __await, __decorate, __metadata } from "tslib";
import Clipboard from 'clipboard';
import gql from 'graphql-tag';
import { css, html } from 'lit';
import { customElement, property, queryAll } from 'lit/decorators.js';
import { asyncReplace } from 'lit/directives/async-replace.js';
import { connect } from 'pwa-helpers/connect-mixin.js';
import { client } from '@operato/graphql';
import { navigate, PageView, store } from '@operato/shell';
import { parseJwt, sleep } from '@operato/utils';
import { i18next } from '@operato/i18n';
let Appliance = class Appliance extends connect(store)(PageView) {
    get context() {
        return {
            title: {
                icon: 'devices',
                text: this.appliance.name
            }
        };
    }
    render() {
        var _a;
        var appliance = this.appliance || {};
        var accessTokenExp = (_a = this._accessTokenInfo) === null || _a === void 0 ? void 0 : _a.exp;
        return html `
      <div>
        <h2><mwc-icon>devices</mwc-icon>&nbsp;${appliance.name}</h2>
        <p page-description>${appliance.description}</p>
      </div>

      <form>
        <div fieldset-container>
          <fieldset>
            <legend>${i18next.t('text.appliance')}</legend>
            <div field-2column>
              <div field grid-span>
                <label for="name">${i18next.t('field.name')}</label>
                <input id="name" type="text" name="name" .value=${appliance.name} />
              </div>

              <div field grid-span>
                <label for="description">${i18next.t('field.description')}</label>
                <input id="description" type="text" name="description" .value=${appliance.description} />
              </div>

              <div field>
                <label for="brand">${i18next.t('field.brand')}</label>
                <input id="brand" type="text" name="brand" .value=${appliance.brand} />
              </div>

              <div field>
                <label for="serial-no">${i18next.t('field.serial-no')}</label>
                <input id="serial-no" type="text" name="serialNo" .value=${appliance.serialNo} />
              </div>

              <div field>
                <label for="model">${i18next.t('field.model')}</label>
                <input id="model" type="text" name="model" .value=${appliance.model} />
              </div>

              <div field>
                <label for="netmask">${i18next.t('field.netmask')}</label>
                <input id="netmask" type="text" name="netmask" .value=${appliance.netmask} />
              </div>
            </div>
          </fieldset>
        </div>

        <div fieldset-container>
          <fieldset>
            <legend>${i18next.t('text.appliance credential')}</legend>
            <div field-2column>
              <div field grid-span>
                <label for="access-token">${i18next.t('label.access token')}</label>
                <input id="access-token" type="text" .value=${appliance.accessToken} readonly />
                <button button-in-field clipboard-copy @click=${e => e.preventDefault()}>
                  ${i18next.t('button.copy')}
                </button>
                ${accessTokenExp
            ? html `<div input-hint>
                      ${i18next.t('text.token expiry time')} ${new Date(accessTokenExp * 1000).toLocaleString()} :
                      ${asyncReplace(this.expTimer(accessTokenExp))}
                    </div>`
            : html ``}
              </div>
            </div>
          </fieldset>
        </div>

        <button @click=${this.deleteAppliance.bind(this)}>${i18next.t('button.delete this appliance')}</button>
        <button @click=${this.generateApplianceSecret.bind(this)}>
          ${i18next.t('button.generate new access token')}
        </button>
        <button @click=${this.updateAppliance.bind(this)}>${i18next.t('button.update')}</button>
      </form>
    `;
    }
    firstUpdated() {
        this.clipboard = new Clipboard(this.copybuttons, {
            target: (trigger => trigger.parentElement.querySelector('input'))
        });
    }
    updated(changes) {
        /*
         * If this page properties are changed, this callback will be invoked.
         * This callback will be called back only when this page is activated.
         */
        if (changes.has('appliance')) {
            const { accessToken } = this.appliance || {};
            this.accessToken = accessToken;
        }
        if (changes.has('accessToken')) {
            this._accessTokenInfo = this.accessToken ? parseJwt(this.accessToken) : {};
        }
    }
    async pageUpdated(changes, lifecycle, before) {
        if (this.active) {
            await this.fetchAppliance();
        }
    }
    async fetchAppliance() {
        const response = await client.query({
            query: gql `
        query ($id: String!) {
          appliance(id: $id) {
            id
            name
            description
            serialNo
            brand
            model
            netmask
            accessToken
          }
        }
      `,
            variables: {
                id: this.lifecycle.resourceId
            }
        });
        this.appliance = response.data.appliance;
    }
    async updateAppliance(e) {
        e.preventDefault();
        const form = this.renderRoot.querySelector('form');
        const formData = new FormData(form);
        const patch = Array.from(formData.entries()).reduce((patch, [key, value]) => {
            patch[key] = value;
            return patch;
        }, {});
        const id = this.lifecycle.resourceId;
        const response = await client.mutate({
            mutation: gql `
        mutation ($id: String!, $patch: AppliancePatch!) {
          updateAppliance(id: $id, patch: $patch) {
            id
            name
            description
            serialNo
            brand
            model
            netmask
            accessToken
          }
        }
      `,
            variables: {
                id,
                patch
            }
        });
        if (response.errors) {
            console.error('update fail');
        }
        else {
            this.appliance = response.data.updateAppliance;
            console.log('update sucess');
        }
    }
    async deleteAppliance(e) {
        e.preventDefault();
        const id = this.lifecycle.resourceId;
        const response = await client.mutate({
            mutation: gql `
        mutation ($id: String!) {
          deleteAppliance(id: $id)
        }
      `,
            variables: {
                id
            }
        });
        if (response.errors) {
            console.error('delete fail');
        }
        else {
            navigate('appliance-home');
        }
    }
    async generateApplianceSecret(e) {
        e.preventDefault();
        const id = this.lifecycle.resourceId;
        const response = await client.mutate({
            mutation: gql `
        mutation ($id: String!) {
          generateApplianceSecret(id: $id) {
            id
            name
            description
            serialNo
            brand
            model
            netmask
            accessToken
          }
        }
      `,
            variables: {
                id
            }
        });
        if (response.errors) {
            console.error('generate-appliance-secret fail');
        }
        else {
            this.appliance = response.data.generateApplianceSecret;
            console.log('generate-appliance-secret sucess');
        }
    }
    expTimer(exp) {
        return __asyncGenerator(this, arguments, function* expTimer_1() {
            const DAY = 24 * 60 * 60;
            const HOUR = 60 * 60;
            const MIN = 60;
            while (this.active) {
                var remain = Math.floor(Number(exp) - Date.now() / 1000);
                const days = Math.floor(remain / DAY);
                remain -= days * DAY;
                const hours = Math.floor(remain / HOUR);
                remain -= hours * HOUR;
                const mins = Math.floor(remain / MIN);
                const secs = remain - mins * MIN;
                yield yield __await(i18next.t('text.remaining time', { days, hours, mins, secs }));
                yield __await(sleep(1000));
            }
        });
    }
};
Appliance.styles = [
    css `
      :host {
        display: flex;
        flex-direction: column;
        overflow-y: auto;

        background-color: var(--main-section-background-color);
        padding: var(--padding-wide);
      }
      h2 {
        margin: var(--title-margin);
        font: var(--title-font);
        color: var(--title-text-color);
      }
      [page-description] {
        margin: var(--page-description-margin);
        font: var(--page-description-font);
        color: var(--page-description-color);
      }

      label {
        font: var(--label-font);
        color: var(--label-color);
        text-transform: var(--label-text-transform);
      }
      input {
        border: var(--border-dark-color);
        border-radius: var(--border-radius);
        margin: var(--input-margin);
        padding: var(--input-padding);
        font: var(--input-font);

        flex: 1;
      }
      select:focus,
      input:focus,
      button {
        outline: none;
      }
      form {
        max-width: var(--content-container-max-width);
      }
      [fieldset-container] {
        background-color: var(--theme-white-color);
        margin: var(--margin-wide) 0 var(--margin-default) 0;
        padding: var(--padding-default);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);
      }
      [fieldset-container] fieldset {
        margin: 0;
        margin-top: -15px;
      }
      fieldset {
        border-radius: var(--border-radius);
        border: var(--border-dark-color);
        margin: var(--fieldset-margin);
        padding: var(--fieldset-padding);
      }
      legend {
        padding: var(--legend-padding);
        font-weight: bold;
        color: var(--legend-color);
      }
      [field-2column] {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-gap: 15px;
      }
      [field] {
        display: flex;
        flex-direction: column;
        position: relative;
      }
      [grid-span] {
        grid-column: span 2;
      }
      button,
      [button-in-field] {
        background-color: var(--button-background-color);
        border: var(--button-border);
        border-radius: var(--button-border-radius);
        padding: var(--button-padding);
        color: var(--button-color);
        font: var(--button-font);
        text-transform: var(--button-text-transform);

        margin: var(--margin-default) 0 var(--margin-default) var(--margin-default);
        float: right;
        text-decoration: none;
      }
      button:hover {
        border: var(--button-activ-border);
        box-shadow: var(--button-active-box-shadow);
      }
      [button-in-field] {
        border-radius: 0 var(--button-border-radius) var(--button-border-radius) 0;
        position: absolute;
        top: 12px;
        right: 0;
        max-height: 36px;
      }
      [input-hint] {
        font: var(--input-hint-font);
        color: var(--input-hint-color);
      }
      @media screen and (max-width: 480px) {
        [field] {
          grid-column: span 2;
        }
      }
    `
];
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], Appliance.prototype, "appliance", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], Appliance.prototype, "accessToken", void 0);
__decorate([
    property({ type: Object }),
    __metadata("design:type", Object)
], Appliance.prototype, "_accessTokenInfo", void 0);
__decorate([
    queryAll('[clipboard-copy]'),
    __metadata("design:type", Object)
], Appliance.prototype, "copybuttons", void 0);
Appliance = __decorate([
    customElement('appliance-page')
], Appliance);
//# sourceMappingURL=appliance.js.map