import { toast } from 'react-toastify';
import FileSaver from 'file-saver';
import { TChats } from '../typescript/redux/chats/types';

const format = (a: string) => a.split(' ').join('').trim()

const firstLetter = (word: string) => word.slice(0, 1).toUpperCase()

const slicedWord = (word: string, max: number, from: number = 0) =>
    word.length < max ? word.slice(from) : word.slice(from, max)
    
const timeStamp = (updatedAt: string) => new Date(updatedAt).toLocaleString("en-US", {
    year:'numeric',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
})

const timeStampEU = (updatedAt: string) => new Date(updatedAt).toLocaleString('en-GB', {
    year:'numeric',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
})

const timeStampEUFilter = (updatedAt: string) => new Date(updatedAt).toLocaleString('en-GB', {
    year:'numeric',
    month: 'short',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    second: '2-digit',
})

const timeStampMessage = (updatedAt: string) => new Date(updatedAt).toLocaleString('en-GB',{
    hour: 'numeric',
    minute: '2-digit',
})


const timeStampFilter = (updatedAt: string) => new Date(updatedAt).toLocaleString("en-US", {
    year:'numeric',
    month: 'short',
    day: 'numeric',
})


const playNotification = (url:string) => {
  const audio = new Audio(url);
  audio.play();
}

const notification = (name: string, onClick: () => void) => {
    toast(`🦄new message from ${name}`, {
    position: "bottom-right",
    autoClose: 5000,
    hideProgressBar: false,
    closeOnClick: true,
    pauseOnHover: true,
    draggable: true,
    progress: undefined,
    onClick
  });
}

const copied = (text:string) => {
    toast(`${text} Copied`, {
    position: "bottom-right",
    autoClose: 2000,
    hideProgressBar: false,
    closeOnClick: true,
    pauseOnHover: true,
    draggable: true,
    progress: undefined,
  });
}

const playNotificationWithoutPermission = (url: string) => {
  const w:any = window
  const audioContext: any = new (w.AudioContext || w.webkitAudioContext)();
    navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then(() => {
        const source = audioContext.createBufferSource();
        source.addEventListener('ended', () => {
            source.stop();
            audioContext.close();
        });
        const request = new XMLHttpRequest();
        request.open('GET', url, true);
        request.responseType = 'arraybuffer';
        request.onload = () => {
            audioContext.decodeAudioData(
                request.response,
                (buffer:any) => {
                    source.buffer = buffer;
                    source.connect(audioContext.destination);
                    source.start();
                },
                (e:any) => {
                    console.log('Error with decoding audio data' + e.message);
                });
        }
        request.send();
    })
    .catch(reason => console.error(`Audio permissions denied: ${reason}`));
}

const handleDownload = async (url: string, type: string) => await FileSaver.saveAs(url, type);

const handleSort = (sortBy: string, data: any,sort:boolean): any => {
    return [...data].sort(function (a: any, b: any) {
      if (sort?a[sortBy] > b[sortBy]:a[sortBy] < b[sortBy]) {
        return -1;
      } else if (sort?a[sortBy] < b[sortBy]:a[sortBy] > b[sortBy]) {
        return 1;
      }
      return 0;
    });
};

const sortByRecent = (chats:TChats,sort:boolean) => [...chats].sort((a, b) => {
  const aCreatedAt = a.lastMessageCreatedAt ? a.lastMessageCreatedAt : a.createdAt
  const bCreatedAt = b.lastMessageCreatedAt ? b.lastMessageCreatedAt : b.createdAt
  const aTime = timeStampEUFilter(aCreatedAt)
  const bTime = timeStampEUFilter(bCreatedAt)
  const direction = sort ? aTime < bTime: aTime > bTime
  return direction ? 1 : -1
})



export {
  format,
  firstLetter,
  slicedWord,
  timeStamp,
  timeStampEU,
  timeStampEUFilter,
  timeStampMessage,
  timeStampFilter,
  playNotification,
  notification,
  copied,
  playNotificationWithoutPermission,
  handleDownload,
  handleSort,
  sortByRecent
}