<template>
  <ion-card >
    <ion-img  :router-link="'/tabs/mat_detail/'+obj.id" alt="Silhouette of mountains" :src="thmb"  v-if="thmb" class="img_16_9"/>
    <ion-card-header :router-link="'/tabs/mat_detail/'+obj.id">
      <ion-card-title>{{ name }}</ion-card-title>
    </ion-card-header>

    <ion-card-content class='ion-text-wrap ion-no-padding ion-padding-horizontal' :router-link="'/tabs/mat_detail/'+obj.id">
      {{ dt }}
    </ion-card-content>
    <ion-button fill="clear" @click="likeMatClick"><ion-icon :icon="heart" :color="isLike ? 'danger' : 'medium'  "></ion-icon> 
      <template v-if="obj.total_likes > 0">
        &nbsp;&nbsp;
      {{  Humanize.compactInteger(obj.total_likes, 1) }} {{ pluralize('Like', obj.total_likes) }}
      </template>
    </ion-button>
  </ion-card>
</template>

<script setup lang="ts">
  import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonIcon, onIonViewWillEnter, IonCard, IonCardHeader, IonCardTitle, IonCardSubtitle, IonCardContent, IonImg, IonButton } from '@ionic/vue';
  import moment from 'moment'
  import { getTrainers, listCourses, isLogin, getPref, likeMat } from '@/composable/settings';
  import { ref, onMounted  } from 'vue'
  import { heart } from 'ionicons/icons';
  import pluralize from 'pluralize';
  import Humanize from 'humanize-plus/dist/humanize';

  const props = defineProps({
    obj: Object,
    courseName: String,
  })

  const dt = ref()
  const thmb = ref()
  const name = ref()
  let pref = null
  const isLike = ref(false)
  onMounted(async() => {
    console.log("--- onmounted ---")
    console.log("name === ", props.obj)

    const obj = props.obj
    if(await isLogin()) {
      pref = await getPref()
      console.debug(" pref = ", pref)
      for(const m of pref.mat_likes) {
        if(obj.id == m.id) {
          isLike.value = true
          break
        }
      }
    }
    let temp  = obj.display_datetime || obj.vimeo_created || obj.created_at 
    dt.value = moment(temp).format('LLL'); 

    if( obj.gifs && obj.gifs.length > 0 ) {
      console.log(obj.gifs)
      if(obj.gifs[0].sizes.length > 2 ) {
        thmb.value = obj.gifs[0].sizes[2].link
      }else {
        thmb.value = obj.gifs[0].sizes[0].link
      }
    }else {
      thmb.value = obj.course_image
    }
    name.value = obj.vimeo_name || props.courseName
  })
  const likeMatClick = async() => {
    console.debug(props.obj)
    pref = await likeMat(props.obj.id)
    console.debug(pref)
    isLike.value = false
    for(const m of pref.mat_likes) {
      if(props.obj.id == m.id) {
        isLike.value = true
        props.obj.total_likes += 1
        break
      }
    }
    if(isLike.value == false) {
      props.obj.total_likes -= 1
    }
  } 
</script>

<style scoped>
#container {
  background-color:#f00;
}
ion-card-title {
  font-size:1.5em;
}
.img_16_9 {
  width:480px;
  height:270px;
  object-fit:cover;
}
</style>
