import { CapacitorHttp } from '@capacitor/core';
//import Axios from "axios";
import axios from "axios";
import { setupCache } from 'axios-cache-interceptor';


import { Preferences } from '@capacitor/preferences';


export const TOKEN = '173cb9e357a861abd91e8008fab9246e0cc116af'
//export const BASE_URL = 'http://192.168.1.35:8020/'
export const BASE_URL = 'http://localhost:8020/'
//export const BASE_URL = 'https://www.tigermuaythai.live/'

export const APPLE_CALLBACK = BASE_URL + "soc_accounts/apple/login/callback/";
//const axios = setupCache(Axios); 
//
//axios.defaults.xsrfHeaderName = "X-CSRFTOKEN";
//axios.defaults.xsrfCookieName = "csrftoken";

export const getProducts = async () => {
  console.log("Get Products")
  const { data } = await axios.get("https://yesno.wtf/api");
  console.log(data)
}

export const setToken = async () => {
   await Preferences.set({
    key: 'user',
    value: JSON.stringify({
      id: 1,
      name: 'Max'
    })
  });
}

export const getObject = async () => {
  const ret = await Preferences.get({ key: 'user' });
  const user = JSON.parse(ret.value);
  return user
}

export const getToken = async () => {
  console.log("get token ")
  const token = await Preferences.get({ key: 'token' });
  console.log(token)
  if( token.value == null || token.value == "" ) {
    //const { data } = await axios.post(BASE_URL + "api-token-auth/", {username: 'root', password: 'Tum 1984'})
    const { data } = await axios.post(BASE_URL + "dj-rest-auth/login/", {username: 'root', password: 'Tum 1984'})
    console.log("get token ", data)
    await Preferences.set({
      key: 'token', 
      value: data.token
    })
    return data.token
  }else {
    return token.value
  }
}
export const initAPI = async () => {
  const r = await axios.get(BASE_URL + "backend/api/")
  console.log("--- init api ---")
  console.log(r)
  console.log("-- cookie ---")
  const cookieHeaders = r.headers['Set-Cookie'];
  console.log(cookieHeaders)
}
export const setUserToken = async(token) => {
  let data = await Preferences.set({
    key: 'user_token', 
    value: token
  })
  let data2 = await Preferences.set({
    key: 'token', 
    value: token
  })
  return data
}
export const getTrainers = async () => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + "backend/api/trainers/", {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data.results
}
export const listMats = async  (ids=[]) => {

  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  console.log("ids ", ids)
  if( ids.length == 0 ) {
    const { data } = await axios.get(BASE_URL + "backend/api/mats/?ordering=-id", {
      headers: { 
      'Authorization': `Token ${token.value}`
      }
    })
    
    return data.results
  }else {
    const { data } = await axios.get(BASE_URL + "backend/api/mats/?ids="+ids.join(), {
      headers: { 
      'Authorization': `Token ${token.value}`
      }
    })
    console.log("results = ", data.results)
    return data.results
  }
}
export const listCourses = async  () => {
  console.log("list courses ... ")
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + "backend/api/courses/?ordering=-id&status=active", {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data.results
}
export const getCourse = async  (pk) => {

  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + "backend/api/courses/"+pk+"/", {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data
}
export const getMat = async(pk) => {

  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + `backend/api/mats/${pk}/`, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data
}

export const storeAPNToken = async (device_token) => {
  
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.post(BASE_URL + "backend/api/device_tokens/",{token: device_token},
  {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data
}


export const listCourseMats = async  (cid) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + "backend/api/courses/"+cid+"/mats/", {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data
}
export const listCourseMatsByLevel = async  (clevels) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + "backend/api/mats/?course_level="+clevels.join(","), {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data
}
export const getTodayProgs = async  (day=null) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  if(day) {
    const { data } = await axios.get(BASE_URL + `backend/api/courses/today_progs/?day=${day}`, {
      headers: { 
      'Authorization': `Token ${token.value}`
      }
    })
    console.log(data)
    return data
  }else {
    const { data } = await axios.get(BASE_URL + "backend/api/courses/today_progs/", {
      headers: { 
      'Authorization': `Token ${token.value}`
      }
    })
    console.log(data)
    return data
  }
}
export const getLive = async  () => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + "backend/api/scheds/get_live/", {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.log(data)
  return data
}
export const getPosts = async (cat) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + `backend/api/posts/?category__slug=${cat}&status=active&ordering=-created_at`, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  return data.results
}
export const getPost = async (pid) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + `backend/api/posts/${pid}/`, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  return data
}
export const searchMat = async (s) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + `backend/api/mats/?search=${s}`, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  return data
}

export const callUrl = async(url) => {
  
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(url, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  return data
}
export const facebookLogin = async(access_token) => {

  const token = await Preferences.get({ key: 'token' });
  console.log("access_code = ", access_token)
  const { data } = await axios.post(BASE_URL + 'dj-rest-auth/facebook/',{access_token: access_token.token}, {
    headers: {
      'Content-Type': 'application/json', 
    }
  })
  //.catch((error) => {
    //console.log("fb error = ", error)
  //})
  console.log("facebook login = ", data)
  return data
}
export const ggLogin = async(access_token, id_token) => {

  const token = await Preferences.get({ key: 'token' });
  console.log("access_code = ", access_token)
  console.log("id token = ", id_token)
  const { data } = await axios.post(BASE_URL + 'dj-rest-auth/google/',{access_token: access_token}, {
    headers: {
      'Content-Type': 'application/json', 
    }
  })
  //.catch((error) => {
    //console.log("gg error = ", error)
  //})
  console.log("gg login = ", data)
  return data
}
export const userLogin = async(username, password) => {

  const { data } = await axios.post(BASE_URL + 'dj-rest-auth/login/',{username: username, password: password}, {
    headers: {
      'Content-Type': 'application/json', 
    }
  })
  console.log("login =  data", data)
  return data
}

export const logout = async() => {

  console.log("--- logout ---")
  const token = await Preferences.get({ key: 'user_token' });
  console.log("user_token = ", token)
  //const { data } = await axios.post(BASE_URL + 'dj-rest-auth/logout/', {}, {
    //headers: { 
    //'Authorization': `Token ${token.value}`
    //}
  //})
  await clearPref()
  const { data } = await axios.post(BASE_URL + 'dj-rest-auth/logout/')
  return data
}
export const clearPref = async() => {

  const clear = await Preferences.clear()
  return clear
}
export const isLogin = async() => {
  const { value } = await Preferences.get({ key: 'user_token' });
  console.log('-- is Login --')
  console.log(value)
  if( value ) 
    return true
  else
    return false
}

export const restSignup = async (username, email, pass1, pass2) => {
  const { data } = await axios.post(BASE_URL + 'dj-rest-auth/registration/',{
    username: username, 
    email: email,
    password1: pass1,
    password2: pass2, 
  }, {
    headers: {
      'Content-Type': 'application/json', 
    }
  })
  return data
}
export const resetPassword = async (email) => {
  console.info(" email ", email)
  const { data } = await axios.post(BASE_URL + 'password-reset/',{
    email: email,
  }, {
    headers: {
      'Content-Type': 'application/json', 
    }
  })
  return data
}


export const getPref = async () => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + `backend/api/profiles/myprofile/`, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  //await Preferences.set({
    //key: 'profile', 
    //value: data 
  //})
  //console.info(data)
  return data
}
export const likeCourse = async (cid) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + `backend/api/profiles/like_course/?cid=${cid}`, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.info(data)
  return data
}
export const likeMat = async (cid) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.get(BASE_URL + `backend/api/profiles/like_mat/?cid=${cid}`, {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.info(data)
  return data
}


export const updateNoti = async (noti) => {
  const token = await Preferences.get({ key: 'token' });
  console.log("token = ", token)
  const { data } = await axios.post(BASE_URL + `backend/api/profiles/update_noti/`,
  {live_noti: noti.liveNoti, 'news_noti':noti.newsNoti},
  {
    headers: { 
    'Authorization': `Token ${token.value}`
    }
  })
  console.info(data)
  return data
}

export const appleLogin = async(access_token) => {

  const token = await Preferences.get({ key: 'token' });
  console.log("access_code = ", access_token)
  const { data } = await axios.post(BASE_URL + 'dj-rest-auth/apple/',{access_token: access_token.authorizationCode, id_token: access_token.identityToken}, {
    headers: {
      'Content-Type': 'application/json', 
    }
  })
  console.log("apple login = ", data)
  return data
}
