<template>
  <b-modal id="export-dashboard" ref="exportDashboard" size="md" hide-footer @hidden="onCancel()">
    <div class="export-dashboard-modal">
      <div class="header">
        <div class="share-dashboard"><p>Share Dashboard</p></div>
        <div class="dashboard-name">
          <span>
            <svg class="icon">
              <use xlink:href="/assets/img/mads-common-icons.svg#union"></use>
            </svg>
          </span>
          <div class="name">
            <span class="heading">Dashboard Name</span>
            <span class="dash-name">{{selectedDashboard.name}}</span>
          </div>
        </div>
      </div>
      <div class="exported-dash" v-if="selectedDashboard.exported_url">
        <div class="dashboard-type-wrap">
          <span v-if="showTypeToggleOption">Dashboard is shared as <b style="text-transform: uppercase">{{dashboardType()}}</b></span>
          <b-button variant="primary" class="margin-right-0" v-if="showTypeToggleOption && dashboardType() === 'public'" @click="changeToPrivate()">Change to private</b-button>
          <b-button variant="primary" class="margin-right-0" v-if="showTypeToggleOption && dashboardType() === 'private'" @click="changeToPublic()">Change to public</b-button>
        </div>

        <div class="app-password-wrap" v-if="showAppPasswordInput">
          <b-form-group label="Please enter password for making changes">
            <b-input placeholder="Enter Mads Password" v-model="appPassword" type="password" v-on:keyup.enter="validateAppPassword"></b-input>
            <span v-if="appPasswordError" class="password-error">Please enter correct password</span>
          </b-form-group>
          <b-button variant="outline-primary" @click="validateAppPassword()">Enter</b-button>
        </div>

        <div class="app-password-wrap" v-if="dashboardType() === 'public' && showNewPasswordInput">
          <b-form-group label="Please set a password for private dashboard">
            <b-input placeholder="Enter Dashboard Password" v-model="privatePassword" type="password" v-on:keyup.enter="makeDashboardPrivate"></b-input>
          </b-form-group>
          <b-button variant="outline-primary" @click="makeDashboardPrivate()">Enter</b-button>
        </div>

        <div class="reveal-password-wrap" v-if="dashboardType() === 'private' && showRevealPasswordOption">
          <span class="text" @click="onRevealPassword()">Reveal Password</span>
        </div>

        <div class="reveal-password-wrap" v-if="dashboardType() === 'private' && passwordRevealed">
          <b-form-group label="Below is the password for this private dashboard">
            <b-input v-model="revealedPassword"></b-input>
          </b-form-group>
        </div>

        <div class="dashboard-url" v-if="showTypeToggleOption">
          <div class="url-info">
            <a :href="selectedDashboard.exported_url.url" target="_blank" class="url">{{selectedDashboard.exported_url.url}}</a>
            <b-button variant="outline-primary" ref="container" @click="copyDashboardUrl(selectedDashboard.exported_url.url)">
              <svg class="icon copy-icon">
                <use xlink:href="/assets/img/mads-common-icons.svg#copy"></use>
              </svg>
              <span>Copy</span>
            </b-button>
          </div>
        </div>
        <div class="mads-footer">
          <b-button variant="outline-primary" @click="onCancel()">Ok</b-button>
        </div>
      </div>
      <div v-else class="body">
        <b-form v-if="!exported">
          <b-form-group label="Private Dashboard">
            <toggle-button v-model="exportParams.is_secure" :value="true" :labels="{checked: 'on', unchecked: 'off'}"/>
          </b-form-group>
          <b-form-group label="Password" v-if="exportParams.is_secure">
            <b-form-input placeholder="Enter Dashboard Password" v-model="exportParams.password" id="password" type="password" required></b-form-input>
            <span class="error-msg" v-if="!validations_password.isValid">
              <span v-for="(error, index) in validations_password.errorMessages" :key="index">{{error}}</span>
            </span>
          </b-form-group>
        </b-form>
        <div v-if="exported" class="dashboard-url">
          <div>Dashboard is shared as <b style="text-transform: uppercase">{{exportParams.is_secure ? 'Private' : 'Public'}}</b></div>
          <div class="url-info">
            <a :href="dashboardUrl" target="_blank" class="url">{{dashboardUrl}}</a>
            <b-button variant="outline-primary" ref="container" @click="copyDashboardUrl(dashboardUrl)">
              <svg class="icon copy-icon">
                <use xlink:href="/assets/img/mads-common-icons.svg#copy"></use>
              </svg>
              <span>Copy</span>
            </b-button>
          </div>
        </div>
        <div class="mads-footer" v-if="!exported">
          <b-button variant="outline-primary" @click="onCancel()">Cancel</b-button>
          <b-button variant="primary" @click="onExport()">Export</b-button>
        </div>
        <div class="mads-footer" v-if="exported">
          <b-button variant="outline-primary" @click="reloadDashboard()">Ok</b-button>
        </div>
      </div>
    </div>
  </b-modal>
</template>

<script>
import dashboardEventBus from '../dashboardBus'

export default {
  data () {
    return {
      exportParams: {
        'is_secure': true,
        'password': ''
      },
      exported: false,
      dashboardUrl: '',
      appPassword: '',
      privatePassword: '',
      revealedPassword: '',
      passwordRevealed: false,
      showAppPasswordInput: false,
      showTypeToggleOption: true,
      showNewPasswordInput: false,
      appPasswordError: false,
      showRevealPasswordOption: true,
      validations_password: {
        required: true,
        errorMessages: [],
        isValid: true
      }
    }
  },
  props: {
    currentUser: {},
    selectedDashboard: {},
    commonService: {},
    dashboardService: {}
  },
  methods: {
    open () {
      this.initData()
      this.$refs.exportDashboard.show()
    },
    onCancel () {
      this.$refs.exportDashboard.hide()
    },
    reloadDashboard () {
      this.$refs.exportDashboard.hide()
      dashboardEventBus.$emit('reload-dashboard')
    },
    onExport () {
      let params = this.exportParams
      let config = { orgId: this.currentUser.org.id, id: this.selectedDashboard.id }
      this.dashboardService.export(config, params)
        .then((response) => {
          this.dashboardUrl = response.url
          this.exported = true
        })
        .catch((error) => {
          let errors = error.source
          this.validations_password = this.$_.merge({}, this.validations_password, {
            errorMessages: errors['password'],
            isValid: false
          })
        })
    },
    dashboardType () {
      return this.selectedDashboard.exported_url && this.selectedDashboard.exported_url.is_secure ? 'private' : 'public'
    },
    makeDashboardPublic () {
      let params = {
        'is_secure': false,
        'password': ''
      }
      let config = { orgId: this.currentUser.org.id, id: this.selectedDashboard.id, uuid: this.selectedDashboard.uuid }

      this.dashboardService.updateExportDashboard(config, params)
        .then((response) => {
          let exportedUrl = this.$_.merge({}, this.selectedDashboard.exported_url, { is_secure: false })
          let updatedDashboard = this.$_.merge({}, this.selectedDashboard, { exported_url: exportedUrl })
          dashboardEventBus.$emit('update-dashboard', updatedDashboard)

          this.exported = false
          this.dashboardUrl = ''
          this.appPassword = ''
          this.privatePassword = ''
          this.revealedPassword = ''
          this.passwordRevealed = false
          this.showAppPasswordInput = false
          this.showTypeToggleOption = true
          this.showNewPasswordInput = false
          this.appPasswordError = false
          this.showRevealPasswordOption = true
        })
    },
    makeDashboardPrivate () {
      let params = {
        'is_secure': true,
        'password': this.privatePassword
      }
      let config = { orgId: this.currentUser.org.id, id: this.selectedDashboard.id, uuid: this.selectedDashboard.uuid }

      this.dashboardService.updateExportDashboard(config, params)
        .then((response) => {
          let exportedUrl = this.$_.merge({}, this.selectedDashboard.exported_url, { is_secure: true })
          let updatedDashboard = this.$_.merge({}, this.selectedDashboard, { exported_url: exportedUrl })
          dashboardEventBus.$emit('update-dashboard', updatedDashboard)

          this.exported = false
          this.dashboardUrl = ''
          this.appPassword = ''
          this.privatePassword = ''
          this.revealedPassword = ''
          this.passwordRevealed = false
          this.showAppPasswordInput = false
          this.showTypeToggleOption = true
          this.showNewPasswordInput = false
          this.appPasswordError = false
          this.showRevealPasswordOption = true
        })
    },
    copyDashboardUrl (url) {
      let container = this.$refs.container
      let copyObj = { url: url, container: container }
      dashboardEventBus.$emit('copy-text', copyObj)
    },
    changeToPrivate () {
      this.updateProcessType = 'change_dashboard_type'

      this.showTypeToggleOption = false
      this.showRevealPasswordOption = false
      this.showAppPasswordInput = true
    },
    changeToPublic () {
      this.updateProcessType = 'change_dashboard_type'

      this.showTypeToggleOption = false
      this.showRevealPasswordOption = false
      this.showAppPasswordInput = true
    },
    onRevealPassword () {
      this.updateProcessType = 'reveal_password'

      this.showRevealPasswordOption = false
      this.showTypeToggleOption = false
      this.showAppPasswordInput = true
    },
    revealPassword () {
      let config = { orgId: this.currentUser.org.id, id: this.selectedDashboard.id, uuid: this.selectedDashboard.uuid }

      this.dashboardService.showCredentials(config)
        .then((response) => {
          this.revealedPassword = response.password

          this.showAppPasswordInput = false
          this.passwordRevealed = true
        })
    },
    onPasswordValidatedChangeType () {
      if (this.dashboardType() === 'public') {
        this.showAppPasswordInput = false
        this.showNewPasswordInput = true
      } else {
        this.makeDashboardPublic()
      }
    },
    onPasswordValidatedRevealPassword () {
      this.revealPassword()
    },
    validateAppPassword () {
      let config = { orgId: this.currentUser.org.id }
      let params = { password: this.appPassword }

      this.commonService.validateCredentials(config, params)
        .then((response) => {
          if (response.id) {
            if (this.updateProcessType === 'change_dashboard_type') {
              this.onPasswordValidatedChangeType()
            } else if (this.updateProcessType === 'reveal_password') {
              this.onPasswordValidatedRevealPassword()
            }
          } else {
            this.appPasswordError = true
          }
        })
    },
    initData () {
      this.exportParams = this.$_.merge({}, {
        'is_secure': true,
        'password': ''
      })
      this.exported = false
      this.dashboardUrl = ''
      this.appPassword = ''
      this.privatePassword = ''
      this.revealedPassword = ''
      this.passwordRevealed = false
      this.showAppPasswordInput = false
      this.showTypeToggleOption = true
      this.showNewPasswordInput = false
      this.appPasswordError = false
      this.showRevealPasswordOption = true
      this.updateProcessType = ''
    }
  }
}
</script>

<style lang="scss" scoped>
  .export-dashboard-modal {
    width: 100%;
    .header {
      .share-dashboard {
        padding: 12px 20px 12px 20px;
        background: #DDE2E5;
        border-radius: 6px 6px 0 0;
        p {
          font-size: 16px;
          margin-bottom: 0;
          font-weight: 900;
        }
      }
      .dashboard-name {
        padding: 0 20px;
        padding: 12px 20px 12px 20px;
        align-items: center;
        display: flex;
        border-bottom: 1px solid rgba(0, 0, 0, 0.1);
        p {
          font-size: 16px;
          margin-bottom: 0;
          font-weight: 900;
        }
        .icon {
          width: 30px;
          height: 30px;
        }
        .name {
          display: flex;
          flex-direction: column;
          margin-left: 10px;
          .heading {
            font-size: 12px;
          }
          .dash-name {
            font-size: 14px;
            font-weight: 700;
          }
        }
      }
    }
    .body {
      padding: 0 20px 20px 20px;
    }
    .exported-dash {
      padding: 0 20px 20px 20px;
    }
    form {
      margin-top: 30px;
    }
    .dashboard-type-wrap {
      margin-top: 30px;
      display: flex;
      align-items: center;
    }
    .app-password-wrap, .reveal-password-wrap {
      margin-top: 10px;
      .password-error {
        padding-top: 10px;
        color: red;
        display: inline-block;
      }
    }
    .reveal-password-wrap {
      span {
        text-decoration: underline;
        color: #3576AB;
        cursor: pointer;
      }
    }
    .change-type-btn {
        background-color: #3576AB !important;
        color: white !important;
        margin: 0 0 0 auto;
        height: 35px;
        padding: 4px 8px;
        min-width: 120px;
      }
    .change-dashboard-type {
      .text {
        color: #4c92c3;
        text-decoration: underline;
        cursor: pointer;
      }
    }
    .dashboard-url {
      display: flex;
      align-items: left;
      margin: 30px 0;
      flex-direction: column;
      .url-info {
        margin-top: 20px;
        display: flex;
      }
      .url {
        overflow: hidden;
        display: inline-block;
        width: 100%;
        background-color: #f2f2f2;
        padding: 10px;
        white-space: nowrap;
        text-overflow: ellipsis;
        border-top-left-radius: 4px;
        border-bottom-left-radius: 4px;
      }
      .copy-btn {
        width: 75px;
        display: inline-block;
        text-align: center;
        cursor: pointer;
        background-color: green;
        height: 40px;
        color: white;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 0 0 auto;
        span {
          padding-left: 5px;
        }
      }
      .copy-icon {
        height: 18px;
        width: 18px;
      }
    }
    .mads-footer {
      text-align: right;
      .save-btn {
        background-color: #4c92c3 !important;
        color: #ffffff !important;
        min-width: 90px;
      }
    }
    .margin-right-0 {
      margin-right: 0;
      margin-left: auto;
    }
  }
</style>

<style lang="scss">
#export-dashboard___BV_modal_header_ {
  .close {
    margin-top: -16px;
    color: #495057;
  }
}
</style>
