<script>
import cBtna from "./c-btna";

export default {
  extends: cBtna,
  data: function() {
    return {
      componentClass: "c-btn-inlogin",
      authorizationUrl: null,
      callbackState: null
    }
  },
  props: {
    dataFieldIdent4ExtSignInInfo: {
      type: String,
      default: "linkedInSignInInfo"
    },
    dataFieldIdent4ExtSignInCallbackInfo: {
      type: String,
      default: "extSignInCallbackInfo"
    }
  },
  computed: {
    getSignInInfo: function() {
      return this.getDataFieldValue(this.dataFieldIdent4ExtSignInInfo)
    }
},
  methods: {
    onClick: function() {
      if(this.authorizationUrl == null) return
      window.location.href = this.authorizationUrl
    },
    signInInfoAdd: function() {
      if(this.getSignInInfo == null || this.getSignInInfo == '') return
      //
      let signInInfo = JSON.parse(this.getSignInInfo)?.signInInfo
      if(signInInfo == null) return
      //
      this.authorizationUrl = signInInfo.authorizationUrl;
      this.callbackState = signInInfo.state;
      this.checkAuthorizationCallback()
    },
    checkAuthorizationCallback: function() {
      let routeQuery = this?.$route?.query
      if (
        routeQuery != null
        && routeQuery.extSingInCallbackIdent == 'LinkedIn'
        && routeQuery.error == null
        && routeQuery.code != null
        && this.callbackState == routeQuery.state
      ) {
        let extSignInCallbackInfo = {
          code: this.$route.query.code
        }
        this.setDataFieldValue({ dataFieldIdent: this.dataFieldIdent4ExtSignInCallbackInfo, dataFieldValue: JSON.stringify(extSignInCallbackInfo)})
        //
        this.$emit('beforeExec')
        if (this.$scopedSlots.confirmation && !this.confirmed) {
          this.showConfirmation = true
        } else {
          let payload = {
            appWindowIdent: this.appWindowIdent,
            dataSetIdent: this.dataSetIdent,
            actionIdent: this.actionIdent,
            row: this.contextRow,
            router: this.$router,
            window: window,
            layoutIdent: this.layoutIdent
          }
          this.showConfirmation = false
          this.confirmed = false
          this.invokeAction(payload)
        }
      }
    }
  },
  watch: {
    getSignInInfo: function() {
      this.signInInfoAdd()
    }
  },
  mounted: async function() {
    if (this.getAppWindow(this.appWindowIdent) == null) {
      await this.addAppWindow({
        appWindowIdent: this.appWindowIdent,
        setActive: false,
        lookupDef: null,
        addRoutingData: false,
        path: null,
        query: null
      })
    }
    this.width = this.$el.offsetHeight
    //
    this.signInInfoAdd()
  },
  updated: function() {
    this.width = this.$el.offsetHeight
  }
}
</script>