import { __asyncGenerator, __await, __decorate, __metadata } from "tslib";
import '@material/web/icon/icon.js';
import Clipboard from 'clipboard';
import gql from 'graphql-tag';
import { css, html } from 'lit';
import { customElement, property, state } 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';
let AppBinding = class AppBinding extends connect(store)(PageView) {
    get context() {
        return {
            title: {
                icon: 'link',
                text: this.appbinding.name
            }
        };
    }
    render() {
        var _a, _b, _c;
        var binding = this.appbinding || {};
        var app = ((_a = this.appbinding) === null || _a === void 0 ? void 0 : _a.application) || {};
        var refreshTokenExp = (_b = this._refreshTokenInfo) === null || _b === void 0 ? void 0 : _b.exp;
        var accessTokenExp = (_c = this._accessTokenInfo) === null || _c === void 0 ? void 0 : _c.exp;
        return html `
      <div>
        <h2><md-icon>link</md-icon>&nbsp;${app.name}</h2>
        <p page-description>${app.description}</p>
      </div>

      ${app.icon
            ? html `
            <div icon>
              <img src=${app.icon} />
            </div>
          `
            : html ``}

      <form>
        <div fieldset-container>
          <fieldset>
            <legend>application</legend>
            <div field-2column>
              <div field grid-span>
                <label for="app-name">app name</label>
                <input id="app-name" type="text" .value=${app.name} readonly />
              </div>

              <div field grid-span>
                <label for="app-description">description</label>
                <input id="app-description" type="text" .value=${app.description} readonly />
              </div>

              <div field>
                <label for="contact-email">contact email</label>
                <input id="contact-email" type="text" .value=${app.email} readonly />
              </div>
            </div>
          </fieldset>
        </div>

        <div fieldset-container>
          <fieldset>
            <legend>binding</legend>
            <div field-2column>
              <div field grid-span>
                <label for="id">id</label>
                <input id="id" type="text" .value=${binding.id} readonly />
              </div>

              <div field grid-span>
                <label for="name">name</label>
                <input id="name" type="text" .value=${binding.email} readonly />
              </div>

              <div field>
                <label for="status">status</label>
                <input id="status" type="text" .value=${binding.status} readonly />
              </div>

              <div field>
                <label for="scope">scope</label>
                <input id="scope" type="text" .value=${binding.scope} readonly />
              </div>
            </div>
          </fieldset>
        </div>

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

              <div field grid-span>
                <label for="refresh-token">refresh token</label>
                <input id="refresh-token" type="text" .value=${binding.refreshToken || ''} readonly />
                <button button-in-field clipboard-copy @click=${e => e.preventDefault()}>copy</button>
                ${refreshTokenExp
            ? html `<div input-hint>
                      expired in ${new Date(refreshTokenExp).toLocaleString()} :
                      ${asyncReplace(this.expTimer(refreshTokenExp))}
                    </div>`
            : html ``}
              </div>
            </div>
          </fieldset>
        </div>

        <button @click=${this.deleteAppBinding.bind(this)}>delete this application binding</button>
        <button @click=${this.renewApplicationAccessToken.bind(this)}>renew access token</button>
      </form>
    `;
    }
    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(`${days} days ${hours} hours ${mins} mins ${secs} seconds remain`);
                yield __await(sleep(1000));
            }
        });
    }
    firstUpdated() {
        const copybuttons = this.renderRoot.querySelectorAll('[clipboard-copy]');
        this.clipboard = new Clipboard(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('appbinding')) {
            const { refreshToken } = this.appbinding || {};
            this._refreshTokenInfo = refreshToken ? parseJwt(refreshToken) : {};
        }
        if (changes.has('accessToken')) {
            this._accessTokenInfo = this.accessToken ? parseJwt(this.accessToken) : {};
        }
    }
    async pageUpdated(changes, lifecycle, before) {
        if (this.active) {
            /*
             * this page is activated
             */
            await this.fetchAppBinding();
        }
        else {
            /* this page is deactivated */
        }
    }
    async fetchAppBinding() {
        const response = await client.query({
            query: gql `
        query ($id: String!) {
          appBinding(id: $id) {
            id
            name
            description
            email
            scope
            status
            application {
              id
              name
              description
              email
              icon
            }
            refreshToken
          }
        }
      `,
            variables: {
                id: this.lifecycle.resourceId
            }
        });
        this.appbinding = response.data.appBinding;
    }
    async deleteAppBinding(e) {
        e.preventDefault();
        const id = this.lifecycle.resourceId;
        const response = await client.mutate({
            mutation: gql `
        mutation ($id: String!) {
          deleteAppBinding(id: $id)
        }
      `,
            variables: {
                id
            }
        });
        const result = response.data.deleteAppBinding;
        if (result) {
            console.log('delete sucess');
            navigate(`app-bindings`);
        }
        else {
            console.error('delete fail');
        }
    }
    async renewApplicationAccessToken(e) {
        e.preventDefault();
        const id = this.lifecycle.resourceId;
        const response = await client.mutate({
            mutation: gql `
        mutation ($id: String!) {
          renewApplicationAccessToken(id: $id) {
            accessToken
            refreshToken
          }
        }
      `,
            variables: {
                id
            }
        });
        if (response.errors) {
            console.error('renew application access token fail');
        }
        else {
            const { accessToken, refreshToken } = response.data.renewApplicationAccessToken;
            this.accessToken = accessToken;
            this.appbinding = Object.assign(Object.assign({}, this.appbinding), { refreshToken });
        }
    }
};
AppBinding.styles = [
    css `
      :host {
        display: flex;
        flex-direction: column;
        overflow-y: auto;

        position: relative;

        background-color: var(--md-sys-color-background);
        padding: var(--spacing-large);
      }

      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);
      }

      [icon] {
        position: absolute;
        top: 10px;
        right: 10px;

        max-width: 80px;
      }

      [icon] img {
        max-width: 100%;
        max-height: 100%;
      }

      [fieldset-container] {
        background-color: var(--md-sys-color-surface);
        margin: var(--spacing-large) 0 var(--spacing-medium) 0;
        padding: var(--spacing-medium);
        border-radius: var(--border-radius);
        box-shadow: var(--box-shadow);

        label {
          font: var(--label-font);
          color: var(--label-color, var(--md-sys-color-on-surface));
          text-transform: var(--label-text-transform);
        }
        input {
          border: var(--border-dim-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] fieldset {
        margin: 0;
        margin-top: -15px;
      }

      fieldset {
        border-radius: var(--border-radius);
        border: var(--border-dim-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(--spacing-medium) 0 var(--spacing-medium) var(--spacing-medium);
        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)
], AppBinding.prototype, "appbinding", void 0);
__decorate([
    property({ type: String }),
    __metadata("design:type", String)
], AppBinding.prototype, "accessToken", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], AppBinding.prototype, "_refreshTokenInfo", void 0);
__decorate([
    state(),
    __metadata("design:type", Object)
], AppBinding.prototype, "_accessTokenInfo", void 0);
AppBinding = __decorate([
    customElement('app-binding-page')
], AppBinding);
//# sourceMappingURL=app-binding.js.map