import { computed, defineComponent, onMounted, PropType, ref, watch } from 'vue'
import { useUserStore } from '@store/UserStore'
import { useCircuitStore } from '@store/CircuitStore'

import { ICircuit, IImgGallery, IUserFields, IUserProfile, IFriends, IAccount } from 'model'
import { costanti } from '@costanti'
import { shared_consts } from '@/common/shared_vuejs'
import { tools } from '@store/Modules/tools'
import { useQuasar } from 'quasar'
import { useI18n } from '@/boot/i18n'
import { useRoute, useRouter } from 'vue-router'
import { CUserNonVerif } from '@/components/CUserNonVerif'
import { CSaldo } from '@/components/CSaldo'
import { toolsext } from '@store/Modules/toolsext'
import { useGlobalStore } from '@store/globalStore'

export default defineComponent({
  name: 'CMyCircuit',
  emits: ['setCmd'],
  components: {CUserNonVerif, CSaldo},
  props: {
    mycircuit: {
      type: Object as PropType<ICircuit | null>,
      required: false,
      default: null,
    },
    circuitname: {
      type: String,
      required: false,
      default: null,
    },
    visu: {
      type: Number,
      required: true,
    }
  },

  setup(props, { emit }) {

    const userStore = useUserStore()
    const circuitStore = useCircuitStore()
    const $q = useQuasar()
    const { t } = useI18n()
    const $router = useRouter()
    const $route = useRoute()

    const globalStore = useGlobalStore()

    const circuit = ref(<ICircuit | null>null)
    const account = computed(() => circuit.value ? userStore.getAccountByCircuitId(circuit.value._id) : null )

    const qtarem = computed(() => account.value ? circuitStore.getRemainingCoinsToSend(account.value) : 0)
    const saldo = computed(() => account.value ? account.value.saldo : 0)

    const table = ref(toolsext.TABCIRCUITS)

    const showingtooltip = ref(false)

    watch(() => props.mycircuit, (newval, oldval) => {
      mounted()
    })

    function mounted() {
      if (!props.mycircuit) {
        if (props.circuitname) {
          circuit.value = null
        }
      } else {
        if (props.mycircuit) {
          circuit.value = props.mycircuit
        }
      }
    }

    function getImgCircuit(circuit: ICircuit) {
      return userStore.getImgByCircuit(circuit)
    }

    function naviga(path: string) {
      $router.push(path)
    }

    function setCmd(cmd: number, myusername: string, value: any = '') {
      emit('setCmd', cmd, myusername, value)
    }

    function myusername() {
      return userStore.my.username
    }

    onMounted(mounted)

    return {
      circuit,
      costanti,
      getImgCircuit,
      naviga,
      setCmd,
      shared_consts,
      userStore,
      tools,
      table,
      myusername,
      circuitStore,
      t,
      account,
      qtarem,
      saldo,
      globalStore,
      showingtooltip,
    }
  },
})
