<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>
        <ion-img src="/images/tmt-logo.png" />
      </ion-title>
       <ion-buttons slot="end">
          <ion-button :router-link="'/tabs/search_page/'">
            <ion-icon slot="icon-only" :icon="search"></ion-icon>
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>
    <ion-content>
      <ion-header collapse="condense">
        <ion-toolbar>
          <ion-title size="large">

        <ion-img src="/images/tmt-logo.png" />
          </ion-title>
        </ion-toolbar>
      </ion-header>
      <template v-if="liveObj && liveObj.result">
        <div v-html="liveObj.result.embed_html"></div>
      </template>
      <div class=''>
      <h2 class='ion-margin-start'>Today Programs</h2>
      <swiper :slides-per-view="2" :loop="true" v-if="todays" class='ion-no-margin'>
      <swiper-slide v-for="m in todays">
        <CourseSchedule :course-obj="m.course_level.course" :from-time="m.from_time" :to-time='m.to_time'  />
      </swiper-slide>
      </swiper>
      </div>
      <template v-if="posts">
        <div class=''>
          <h2 class="ion-margin-start">Muaythai Techniques</h2>
          <swiper :slides-per-view="'auto'"  :loop="true" >
          <swiper-slide v-for="m in posts" class='ion-no-padding'>
            <Post :obj="m" />
          </swiper-slide>
          </swiper>
        </div>
      </template>
      <template v-if="mats">
        <h2 class='ion-padding-start'>Trainings</h2>
      <ion-grid>

        <ion-row>
          <ion-col size="12" size-md="4" size-lg="2" v-for="c in mats">
            <CourseMat :obj="c" :course-name="c.course_name" class='ion-no-margin' />
          </ion-col>
        </ion-row>
      </ion-grid>
      </template>

    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">

  import { IonPage, IonHeader, IonToolbar, IonTitle, IonContent, IonIcon, onIonViewWillEnter, IonButton, 
  onIonViewWillLeave, IonItem, IonLabel, IonThumbnail, IonCol, IonGrid, IonRow, IonCard, IonCardContent, IonCardHeader, IonCardSubtitle, IonCardTitle, onIonViewDidEnter,  IonButtons, IonImg, useIonRouter } from '@ionic/vue';

import ExploreContainer  from '@/components/ExploreContainer.vue';
import CourseSchedule from '@/components/CourseSchedule.vue'
import Post from '@/components/Post.vue'
import CourseMat from '@/components/CourseMat.vue'
import SearchEngine from '@/components/SearchEngine.vue'

import { CapacitorHttp } from '@capacitor/core';
import { ref } from 'vue';
import { TOKEN, getProducts, setToken, getObject, getToken, getTrainers, listMats, storeAPNToken,
getTodayProgs, getLive, getPosts, initAPI, clearPref, isLogin} from '@/composable/settings';
//import VueCoreVideoPlayer from 'vue-core-video-player'
import { vueVimeoPlayer } from 'vue-vimeo-player'

import { GoogleAuth } from '@codetrix-studio/capacitor-google-auth';

import { PushNotifications } from '@capacitor/push-notifications';

import Player from '@vimeo/player';

import { Autoplay, Keyboard, Pagination, Scrollbar, Zoom } from 'swiper/modules';
import { Swiper, SwiperSlide } from 'swiper/vue';
import 'swiper/css';
import 'swiper/css/autoplay';
import 'swiper/css/keyboard';
import 'swiper/css/pagination';
import 'swiper/css/scrollbar';
import 'swiper/css/zoom';
import '@ionic/vue/css/ionic-swiper.css';
import { search } from 'ionicons/icons';

const safeUrl = "https://vimeo.com/880005259?share=copy"
const token = ref()
const trainers = ref([])
const mats = ref()
const todays = ref()
const posts = ref()
const scrollToBottom = () => {
  console.log("scroll")
  //content.value.$el.scrollToBottom(300);
};
const items = ref([{msg: 'foo'}, {msg: 'bar2'}])

const ionRouter = useIonRouter();

const options = {
      id: 59777392,
      width: 640,
      loop: true
  };
 //const video = ref(null)

  //const player = new Player(video, options);

const liveObj = ref()
const modules =  [Autoplay, Keyboard, Pagination, Scrollbar, Zoom]
  onIonViewWillEnter(async () => {
    let v = await isLogin()
    console.log("v === ", v)
    if( v == false ) {
      ionRouter.navigate('/tabs/tab4', 'forward', 'replace');
    }
    //console.log("video " ,video)
    //console.log("video id", video.value.id)
    //const player = new Player(video.value.id, options);
    //player.setVolume(0);

    //player.on('play', function() {
    //    console.log('played the video!');
    //});
    console.log("view view enter")
    // doGet()
    // await getProducts()
    // console.log(TOKEN)
    // setToken()
    // let u = getObject()
    //console.log('u ', u)
    await initAPI()
    token.value = await getToken()
    
    try{
      trainers.value = await getTrainers()
    }catch(error){
      console.log("trainers ", error)
      await clearPref()
      token.value = await getToken()
    }

    listMats().then( (data) => {
      mats.value = data
    })
    getPosts("muaythai-techniques").then( (data) => {
      posts.value = data   
    })
    console.log(" trainers => ", trainers)

    GoogleAuth.initialize();
    registerNotifications()
    addListeners()

    getTodayProgs().then( (data) => {
      todays.value = data
    })
    setInterval( async () => {
      console.log("did enter")
      if( liveObj.value == null ||  liveObj.value.result == false ) {
        liveObj.value = await getLive()
      }
    }, 100000)
  })

  onIonViewWillLeave(() => {
    console.log("view will leave")

  })

  onIonViewDidEnter(async() => {
  })

  const doGet = async () => {
    console.log("do get")
    const options = {
      url: 'https://example.com/my/api',
      headers: { 'X-Fake-Header': 'Fake-Value' },
      params: { size: 'XL' },
    };

    const response: HttpResponse = await CapacitorHttp.get(options);
    console.log(response)
  }
const addListeners = async () => {
  await PushNotifications.addListener('registration', token => {
    console.info('Registration token: ', token.value);
    storeAPNToken(token.value)
  });

  await PushNotifications.addListener('registrationError', err => {
    console.error('Registration error: ', err.error);
  });

  await PushNotifications.addListener('pushNotificationReceived', notification => {
    console.log('Push notification received: ', notification);
  });

  await PushNotifications.addListener('pushNotificationActionPerformed', notification => {
    console.log('Push notification action performed', notification.actionId, notification.inputValue);
  });
}

const registerNotifications = async () => {
  let permStatus = await PushNotifications.checkPermissions();

  if (permStatus.receive === 'prompt') {
    permStatus = await PushNotifications.requestPermissions();
  }

  if (permStatus.receive !== 'granted') {
    throw new Error('User denied permissions!');
  }

  await PushNotifications.register();
}

const getDeliveredNotifications = async () => {
  const notificationList = await PushNotifications.getDeliveredNotifications();
  console.log('delivered notifications', notificationList);
}
</script>

<style scoped>
#post_slide {
   aspect-ratio:4/3 auto;
}
.img_16_9 {
  width:480px;
  height:270px;
  object-fit:cover;
}
.swiper-slide {
  width: 90% !important;
	&:last-child {
	  width: 100% !important;
	}
}
</style>
