{% extends "base.html" %} {% from "macros.jinja" import window_vars with context
%} {% block page %}
<div class="row q-col-gutter-md">
  <div class="col-12 col-md-7 q-gutter-y-md">
    <q-card>
      <q-card-section>
        <q-btn unelevated color="primary" @click="formDialog.show = true"
          >New satsdice</q-btn
        >
      </q-card-section>
    </q-card>

    <q-card>
      <q-card-section>
        <div class="row items-center no-wrap q-mb-md">
          <div class="col">
            <h5 class="text-subtitle1 q-my-none">satsdices</h5>
          </div>
        </div>
        <q-table
          dense
          flat
          :data="payLinks"
          row-key="id"
          :pagination.sync="payLinksTable.pagination"
        >
          {% raw %}
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th style="width: 10%"></q-th>
              <q-th auto-width style="text-align: left">Title</q-th>
              <q-th auto-width style="text-align: left">Min bet</q-th>
              <q-th auto-width style="text-align: left">Max bet</q-th>
              <q-th auto-width style="text-align: left">Multiplier</q-th>
              <q-th auto-width style="text-align: left">Haircut</q-th>
              <q-th auto-width style="text-align: left">Chance</q-th>
              <q-th auto-width style="text-align: left"></q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <q-td style="width: 10%">
                <q-btn
                  unelevated
                  dense
                  size="xs"
                  icon="visibility"
                  :color="($q.dark.isActive) ? 'grey-7' : 'grey-5'"
                  @click="openQrCodeDialog(props.row.id)"
                ></q-btn>
              </q-td>

              <q-td auto-width>{{ props.row.title }}</q-td>
              <q-td auto-width>{{ props.row.min_bet }}</q-td>
              <q-td auto-width>{{ props.row.max_bet }}</q-td>
              <q-td auto-width>*{{ props.row.multiplier }}</q-td>
              <q-td auto-width>{{ props.row.haircut }}</q-td>
              <q-td auto-width>{{ props.row.chance }}%</q-td>
              <q-td auto-width>
                <q-btn
                  flat
                  dense
                  size="xs"
                  @click="openUpdateDialog(props.row.id)"
                  icon="edit"
                  color="light-blue"
                ></q-btn>
                <q-btn
                  flat
                  dense
                  size="xs"
                  @click="deletePayLink(props.row.id)"
                  icon="cancel"
                  color="pink"
                ></q-btn>
              </q-td>
            </q-tr>
          </template>
          {% endraw %}
        </q-table>
      </q-card-section>
    </q-card>
  </div>

  <div class="col-12 col-md-5 q-gutter-y-md">
    <q-card>
      <q-card-section>
        <h6 class="text-subtitle1 q-my-none">
          {{SITE_TITLE}} Sats Dice extension
        </h6>
      </q-card-section>
      <q-card-section class="q-pa-none">
        <q-separator></q-separator>
        <q-list>
          {% include "satsdice/_api_docs.html" %}
          <q-separator></q-separator>
          {% include "satsdice/_lnurl.html" %}
        </q-list>
      </q-card-section>
    </q-card>
  </div>

  <q-dialog v-model="formDialog.show" position="top" @hide="closeFormDialog">
    <q-card class="q-pa-lg q-pt-xl lnbits__dialog-card">
      <q-form @submit="sendFormData" class="q-gutter-md">
        <q-select
          filled
          dense
          emit-value
          v-model="formDialog.data.wallet"
          :options="g.user.walletOptions"
          label="Wallet *"
        >
        </q-select>
        {% raw %}
        <q-input
          filled
          dense
          v-model.trim="formDialog.data.title"
          type="text"
          label="Title *"
        ></q-input>

        <div class="row">
          <div class="col">
            <q-input
              class="q-pr-xs"
              filled
              dense
              v-model.trim="formDialog.data.min_bet"
              type="number"
              label="Min bet size (sats)"
            ></q-input>
          </div>
          <div class="col">
            <q-input
              class="q-pl-xs"
              filled
              dense
              v-model.trim="formDialog.data.max_bet"
              type="number"
              label="Max bet size (sats)"
            ></q-input>
          </div>
        </div>

        <q-input
          filled
          dense
          v-model.trim="formDialog.data.haircut"
          type="number"
          label="Haircut (chance of winning % to remove)"
        ></q-input>
        <center>
          <q-badge color="secondary" class="q-mb-lg">
            Multipler: x{{ multiValue }}, Chance of winning: {{ chanceValueCalc
            | percent }}
          </q-badge>

          <q-slider
            style="width: 95%"
            class="q-pt-lg"
            v-model="multiValue"
            :min="1.5"
            :max="20"
            :step="2"
            label
            label-always
            color="primary"
            markers
            snap
          ></q-slider>
        </center>

        <div class="row q-mt-lg">
          <q-btn
            v-if="formDialog.data.id"
            unelevated
            color="primary"
            type="submit"
            >Update flip link</q-btn
          >
          <q-btn
            v-else
            unelevated
            color="primary"
            :disable="
                formDialog.data.wallet == null ||
                formDialog.data.title == null || formDialog.data.min < 10 || formDialog.data.max < formDialog.data.min"
            type="submit"
            >Create satsdice</q-btn
          >
          <q-btn v-close-popup flat color="grey" class="q-ml-auto"
            >Cancel</q-btn
          >
        </div>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="qrCodeDialog.show" position="top">
    <q-card v-if="qrCodeDialog.data" class="q-pa-lg lnbits__dialog-card">
      <q-responsive :ratio="1" class="q-mx-xl q-mb-md">
        <qrcode
          :value="qrCodeDialog.data.lnurl"
          :options="{width: 800}"
          class="rounded-borders"
        ></qrcode>
      </q-responsive>
      <p style="word-break: break-all">
        <strong>ID:</strong> {{ qrCodeDialog.data.id }}<br />
        <strong>Amount:</strong> {{ qrCodeDialog.data.amount }}<br />
        <span v-if="qrCodeDialog.data.currency"
          ><strong>{{ qrCodeDialog.data.currency }} price:</strong> {{
          fiatRates[qrCodeDialog.data.currency] ?
          fiatRates[qrCodeDialog.data.currency] + ' sat' : 'Loading...' }}<br
        /></span>
        <strong>Accepts comments:</strong> {{ qrCodeDialog.data.comments }}<br />
        <strong>Dispatches webhook to:</strong> {{ qrCodeDialog.data.webhook
        }}<br />
        <strong>On success:</strong> {{ qrCodeDialog.data.success }}<br />
      </p>
      {% endraw %}
      <div class="row q-mt-lg q-gutter-sm">
        <q-btn
          outline
          color="grey"
          @click="copyText(qrCodeDialog.data.lnurl, 'Satsdice copied to clipboard!')"
          class="q-ml-sm"
          >Copy Satsdice LNURL</q-btn
        >
        <q-btn
          outline
          color="grey"
          icon="link"
          @click="copyText(qrCodeDialog.data.pay_url, 'Link copied to clipboard!')"
          ><q-tooltip>Copy shareable link</q-tooltip></q-btn
        >

        <q-btn
          outline
          color="grey"
          icon="launch"
          type="a"
          :href="qrCodeDialog.data.pay_url"
          target="_blank"
          ><q-tooltip>Launch shareable link</q-tooltip></q-btn
        >
        <q-btn
          outline
          color="grey"
          icon="print"
          type="a"
          :href="qrCodeDialog.data.print_url"
          target="_blank"
          ><q-tooltip>Print Satsdice</q-tooltip></q-btn
        >
        <q-btn v-close-popup flat color="grey" class="q-ml-auto">Close</q-btn>
      </div>
    </q-card>
  </q-dialog>
</div>

{% endblock %} {% block scripts %} {{ window_vars(user) }}

<script>
  /* globals Quasar, Vue, _, VueQrcode, windowMixin, LNbits, LOCALE */
  Vue.component(VueQrcode.name, VueQrcode)

  var locationPath = [
    window.location.protocol,
    '//',
    window.location.host,
    window.location.pathname
  ].join('')

  var mapPayLink = obj => {
    obj._data = _.clone(obj)
    obj.date = Quasar.utils.date.formatDate(
      new Date(obj.time * 1000),
      'YYYY-MM-DD HH:mm'
    )
    obj.amount = new Intl.NumberFormat(LOCALE).format(obj.amount)
    obj.print_url = [locationPath, 'print/', obj.id].join('')
    obj.pay_url = [locationPath, obj.id].join('')
    console.log(obj)
    return obj
  }

  new Vue({
    el: '#vue',
    mixins: [windowMixin],
    data() {
      return {
        chanceValue: 0,
        multiValue: 1.5,
        currencies: [],
        fiatRates: {},
        checker: null,
        payLinks: [],
        payLinksTable: {
          pagination: {
            rowsPerPage: 10
          }
        },
        formDialog: {
          show: false,
          fixedAmount: true,
          data: {
            haircut: 0,
            min_bet: 10,
            max_bet: 1000,
            currency: 'satoshis',
            comment_chars: 0
          }
        },
        qrCodeDialog: {
          show: false,
          data: null
        }
      }
    },
    filters: {
      percent(val) {
        return val + '%'
      }
    },
    computed: {
      chanceValueCalc() {
        this.chanceValue = (
          (1 / this.multiValue) * 100 -
          this.formDialog.data.haircut -
          (1 / this.multiValue) * 10
        ).toFixed(2)
        return this.chanceValue
      }
    },
    methods: {
      chanceValueTableCalc(multiplier, haircut) {
        return ((1 / multiplier) * 100 - haircut).toFixed(2)
      },
      getPayLinks() {
        LNbits.api
          .request(
            'GET',
            '/satsdice/api/v1/links?all_wallets=true',
            this.g.user.wallets[0].inkey
          )
          .then(response => {
            console.log(response.data)
            this.payLinks = response.data.map(mapPayLink)
          })
          .catch(err => {
            clearInterval(this.checker)
            LNbits.utils.notifyApiError(err)
          })
      },
      closeFormDialog() {
        this.resetFormData()
      },
      openQrCodeDialog(linkId) {
        var link = _.findWhere(this.payLinks, {id: linkId})
        console.log(link)
        if (link.currency) this.updateFiatRate(link.currency)

        this.qrCodeDialog.data = {
          id: link.id,
          amount:
            (link.min === link.max ? link.min : `${link.min} - ${link.max}`) +
            ' ' +
            (link.currency || 'sat'),
          currency: link.currency,
          comments: link.comment_chars
            ? `${link.comment_chars} characters`
            : 'no',
          webhook: link.webhook_url || 'nowhere',
          success:
            link.success_text || link.success_url
              ? 'Display message "' +
                link.success_text +
                '"' +
                (link.success_url ? ' and URL "' + link.success_url + '"' : '')
              : 'do nothing',
          lnurl: link.lnurl,
          pay_url: link.pay_url,
          print_url: link.print_url
        }
        this.qrCodeDialog.show = true
      },
      openUpdateDialog(linkId) {
        const link = _.findWhere(this.payLinks, {id: linkId})
        if (link.currency) this.updateFiatRate(link.currency)

        this.formDialog.data = _.clone(link._data)
        this.formDialog.show = true
        this.formDialog.fixedAmount =
          this.formDialog.data.min === this.formDialog.data.max
      },
      sendFormData() {
        const wallet = _.findWhere(this.g.user.wallets, {
          id: this.formDialog.data.wallet
        })
        var data = _.omit(this.formDialog.data, 'wallet')
        data.min_bet = parseInt(data.min_bet)
        data.max_bet = parseInt(data.max_bet)
        data.multiplier = parseFloat(this.multiValue)
        data.haircut = parseFloat(data.haircut)
        data.chance = parseFloat(this.chanceValue)
        data.base_url = window.location.origin

        if (data.currency === 'satoshis') data.currency = null
        if (isNaN(parseInt(data.comment_chars))) data.comment_chars = 0

        if (data.id) {
          this.updatePayLink(wallet, data)
        } else {
          this.createPayLink(wallet, data)
        }
      },
      resetFormData() {
        this.formDialog = {
          show: false,
          fixedAmount: true,
          data: {
            haircut: 0,
            min_bet: 10,
            max_bet: 1000,
            currency: 'satoshis',
            comment_chars: 0
          }
        }
      },
      updatePayLink(wallet, data) {
        let values = _.omit(
          _.pick(
            data,
            'chance',
            'base_url',
            'multiplier',
            'haircut',
            'title',
            'min_bet',
            'max_bet',
            'webhook_url',
            'success_text',
            'success_url',
            'comment_chars',
            'currency'
          ),
          (value, key) =>
            (key === 'webhook_url' ||
              key === 'success_text' ||
              key === 'success_url') &&
            (value === null || value === '')
        )

        LNbits.api
          .request(
            'PUT',
            '/satsdice/api/v1/links/' + data.id,
            wallet.adminkey,
            values
          )
          .then(response => {
            this.payLinks = _.reject(this.payLinks, obj => obj.id === data.id)
            this.payLinks.push(mapPayLink(response.data))
            this.formDialog.show = false
            this.resetFormData()
          })
          .catch(err => {
            LNbits.utils.notifyApiError(err)
          })
      },
      createPayLink(wallet, data) {
        LNbits.api
          .request('POST', '/satsdice/api/v1/links', wallet.adminkey, data)
          .then(response => {
            this.payLinks.push(mapPayLink(response.data))
            this.formDialog.show = false
            this.resetFormData()
            this.getPayLinks()
          })
          .catch(err => {
            LNbits.utils.notifyApiError(err)
          })
      },
      deletePayLink(linkId) {
        var link = _.findWhere(this.payLinks, {id: linkId})

        LNbits.utils
          .confirmDialog('Are you sure you want to delete this pay link?')
          .onOk(() => {
            LNbits.api
              .request(
                'DELETE',
                '/satsdice/api/v1/links/' + linkId,
                _.findWhere(this.g.user.wallets, {id: link.wallet}).adminkey
              )
              .then(response => {
                this.payLinks = _.reject(
                  this.payLinks,
                  obj => obj.id === linkId
                )
              })
              .catch(err => {
                LNbits.utils.notifyApiError(err)
              })
          })
      },
      updateFiatRate(currency) {
        LNbits.api
          .request('GET', '/satsdice/api/v1/rate/' + currency, null)
          .then(response => {
            let rates = _.clone(this.fiatRates)
            rates[currency] = response.data.rate
            this.fiatRates = rates
          })
          .catch(err => {
            LNbits.utils.notifyApiError(err)
          })
      }
    },
    created() {
      if (this.g.user.wallets.length) {
        var getPayLinks = this.getPayLinks
        getPayLinks()
        // this.checker = setInterval(() => {
        //   getPayLinks()
        // }, 20000)
      }
    }
  })
</script>
{% endblock %}
