import Toastify from 'toastify-js'
import useState from '~/hooks/useState'
import { checkAuth} from '~/hooks/utilsAuth'
import { MessageType} from '~/typs'
import 'toastify-js/src/toastify.css'

export const show_message = (typ: MessageType, msg: string, timeout?: number, cllbck?: any): void => {
  let cssClass = 'msg-box'
  switch (typ) {
    case MessageType.Show:
		  cssClass += ' msg-show'
      break
    case MessageType.Success:
		  cssClass += ' msg-ok'
      break
    case MessageType.Error:
		  cssClass += ' msg-error'
      break
    case MessageType.Warning:
		  cssClass += ' msg-warn'
      break
    case MessageType.Info:
		  cssClass += ' msg-info'
      break
  }
  // https://github.com/apvarun/toastify-js
  Toastify({
    text: msg,
    duration: timeout || 3000,
    //destination: '',
    //selector: '',
    // newWindow: true,
    // close: true,
    className: cssClass,
    offset: {
      x: 10, // horizontal axis - can be a number or a string indicating unity. eg: '2em'
      y: 50, // vertical axis - can be a number or a string indicating unity. eg: '2em
    },
    gravity: 'top', // `top` or `bottom`
    position: 'left', // `left`, `center` or `right`
    // backgroundColor: 'linear-gradient(to right, #00b09b, #96c93d)',
    stopOnFocus: true, // Prevents dismissing of toast on hover
		callback: cllbck
    // onClick() {}, // Callback after click
  }).showToast()
}

export const translate = (store: any, map: string, ky: string, ctx: string, dflt?: string): string => {
  const val = dflt || ky
  const lang: any = {}
  if (lang && lang.value)
    return lang.value[ctx] && lang.value[ctx][ky] ? lang.value[ctx][ky] : val
  else if (lang && lang[ctx])
    return lang[ctx][ky] ? lang[ctx][ky] : val
  else
    return val
}
export const fetch_text = async(path: RequestInfo): Promise<any> => {
  try {
    const response = await fetch(path)
    return !response.ok ? response.text() : new Error('No items found')
  }
  catch (err) {
    return err
  }
}
const request_headers = async (with_auth: boolean): Promise<[any, string]> => {
	const headers: any = {} // { 'Content-Type': 'application/json' }
	headers['Accept']='application/json'
	let error= ''
  if (with_auth) {
    const token = await checkAuth()
		if (token && token.length > 0) {
		  headers['Authorization'] =`Bearer ${token}`
		} else {
		  return [null,`error no auth found`]
		} 
	}
	return [headers, error]
}
export const fetch_json = async(path: RequestInfo, timeout = 2000, with_auth = false, cllbck?: any): Promise<any> => {
	useState().connection.value.state = ''
	let res = null
	let error = ''
	const showError = (err: string) => {
	  show_message(MessageType.Error, `'Data Load' -> ${err}`,5000)
    useState().connection.value.state = 'connection.error'
	}
	const [headers,errorHeader] = await request_headers(with_auth)
	if (errorHeader.length > 0) {
		return [null,errorHeader]
	}
	try {
    const response = await self.fetch(path, {
			method: 'GET',
      headers,
	    //mode: 'cors',
    })
		res = await response.json()
		if (!response.ok && res.message.length > 0)
		   error=res.message
	}
	catch (err: any) {
		error = err
	}
	if (error.length > 0)
		showError(error)
	return [res,error]
}
export const send_data = async(url: string, formData: any, with_auth = true, show = true, cllbck?: any): Promise<any> => {
	const [headers,errorHeader] = await request_headers(with_auth)
	if (errorHeader.length > 0) {
		return [null,errorHeader]
	}
	headers['Content-Type'] = 'application/json' 
  let formDataJsonString = ''
  try {
    formDataJsonString = JSON.stringify(formData)
  }
  catch (e) {
    console.log(e)
		return [null,e]
  }
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers,
      body: formDataJsonString,
    })
    if (!response.ok && response.status !== 200) {
      const errorMessage = await response.json()
      console.log(errorMessage)
			if (show)
        show_message(MessageType.Error, `Send data -> ${errorMessage.error ? errorMessage.error : ''}`)
		  return [null,errorMessage]
      // throw new Error(errorMessage)
    } else if (response.ok && response.status === 200) {
      const res = await response.json()
			if (cllbck) {
				cllbck(res)
			}
			return [res,null]
		}
  }
  catch (e) {
		if (show)
  	  show_message(MessageType.Error, `Send data -> ${e}`)
    useState().connection.value.state = 'connection.error'
    console.log(e)
		return [null,e]
  }
}
export const run_task = (val: number, task: Function) => {
  const now = new Date().getTime()
  const timePassed = now % val
  const run_at = val - timePassed
  setTimeout(task, run_at)
}

export const parse_str_json_data = (src: string, dflt: object|any):object|any => {
	let data = dflt
	try {
		data = JSON.parse(src)
	}
	catch (e) {
		data = dflt
	}
	return data
}
export default {
  fetch_text,
  fetch_json,
  send_data,
  show_message,
  translate,
  run_task,
	parse_str_json_data,
}
