import { PUBLIC_URL } from '$env/static/public';

export async function GetInviteLink(chatId) {
  let token = localStorage.getItem("BPChat")
  const response = await fetch(`${PUBLIC_URL}/api/chat/create_invitation_link?chat_id=${chatId}`,
  {
    method:"GET",
    credentials:"include",
    headers:{
      'accept': 'application/json',
      'Authorization': token,
  }})

  if(response.ok){
    let data = await response.json()
    return data.invitation_link
  } else {
    console.log(response.status)
    return false
  }
}

export async function addingToChat(code){
 
  let token = localStorage.getItem("BPChat")
  const response = await fetch(`${PUBLIC_URL}/api/chat/invite_to_chat/${code}`,
  {
    method:"GET",
    credentials:"include",
    headers:{
      'accept': 'application/json',
      'Authorization': token,
    }
  })

  if(response.ok){
     window.location.href = '/c'
  } else {
    return false
  }

}

export async function getLastMessages(chatId,msgLoaded){
   
   let token = localStorage.getItem('BPChat')
   const response = await fetch(`${PUBLIC_URL}/api/chat/get_some_messages/${chatId}?messages_loaded=${msgLoaded}&messages_to_get=15`,
   {
     method:'GET',
     credentials:'include',
     headers: {'accept': 'application/json',
               'Authorization': token,
     },
   })

   if(response.ok){
     let data = await response.json()
     let msgMassive = data.messages
     //console.log(msgMassive, " аа сообщения", chatId, " - айди")

     if(msgMassive === null){
      return []
     } else { 
      return msgMassive
     }
   }

    else if(response.status === 404){
    console.log(response)
   }
    
    else if(!response.ok)
    console.log(response.status)
    
   }

 export async function getMessageById(chatId,msgId){

  let token = localStorage.getItem('BPChat')
  const response = await fetch(`${PUBLIC_URL}/chat/message/${chatId}?message_id=${msgId}`,{
    method:"GET",
    credentials:'include',
    headers: {'Authorization': token },
    
  })

  if(response.ok){
    let data = await response.json(); 
    return data;
  }
  else{
    return { message: "Сообщение не найдено" };
  }

 }

 export async function MessagePicToUrl(messagePic){

     let token = localStorage.getItem('BPChat')

     const DataForm = new FormData();
     DataForm.append('file', messagePic)

     const response = await fetch('${PUBLIC_URL}/api/images/upload_image',
     {
       method:"POST",
       body:DataForm,
       headers: {'Authorization': token },
     })

     if(!response.ok)
     console.log("ошибка", response.status)
  

     if(response.ok){
       const data = await response.json();
       //console.log("картинка принята")
       return data.image_url;
       
     }
 }

 export async function getAllChats(token){
  
  const response = await fetch(`${PUBLIC_URL}/api/chat`,
  {
    method:"GET",
    credentials:'include',
    headers: {'Authorization': token },

  })
  if(response.ok){
    let data = await response.json();
    data = data.allowed_chats
    //console.log(data)

    if(data == null)
      return []
    else
      return data
    
  } else if(response.status == 409){
    return false //если пользователь не подтвердил почту
  } else {
    console.log(response)
  }
 }

 export async function getPinnedMsg(ID){

  let token = localStorage.getItem('BPChat')
  const response = await fetch(`${PUBLIC_URL}/api/chat/pinned_messages/${ID}`,{
    method:"GET",
    credentials:'include',
    headers: {'Authorization': token },
  })

  if(response.ok){
    let data = await response.json()
    data = data.pinned_messages
    if(data === null){
      return []
    } else {
      return data
    }
  } else {
    console.log(response.status)
  }
 }

 export async function pinMessage(chatId,messageId){

  let token = localStorage.getItem('BPChat')
  const response = await fetch(`${PUBLIC_URL}/api/chat/pinn_message?chat_id=${chatId}&message_id=${messageId}`,{
  method:"POST",
  credentials:'include',
  headers: {'Authorization': token },
  })
  if(response.ok){
    const data = await response.json()
    return data.pinned_message
  } else
      console.log(response.status)

 }

 export async function unpinMessage(chatId, messageId){

  let token = localStorage.getItem('BPChat')
  const response = await fetch(`${PUBLIC_URL}/api/chat/unpinn_message?chat_id=${chatId}&message_id=${messageId}`,{
    method:"DELETE",
    credentials:'include',
    headers: {'Authorization': token },
    })
    if(response.ok){
      return await response.json();
    }
    else
      console.log(response.status)
  
   }
 
   export async function uploadImages(image) {

    let token = localStorage.getItem('BPChat')
    const formData = new FormData();
      formData.append('file', image);

    const response = await fetch(`${PUBLIC_URL}/api/images/upload_image`, {
      method: 'POST',
      credentials: 'include',
      body: formData,
      headers: {'Authorization': token },
    });
  
    if (response.ok) {
      let data = await response.json();
      return data.image_url
    } else {
      console.log(response);
    }
  }
  
  export async function getAllUsers(nameToFind){

    const response = await fetch(`${PUBLIC_URL}/api/users?username=${nameToFind}`,{
      method:"GET",
      credentials:'include'
    })

    if(response.ok){
      let data = await response.json()
      let anotherData = data.users
      
      if(anotherData == null){
        return []
      }
      return data.users
    }

  }

  export async function createNewChat(chatName, excludeUser, token){
    const response = await fetch(`${PUBLIC_URL}/api/chat/create_chat?user_to_exclude=${excludeUser}&chat_name=${chatName}`,{
      method: 'POST',
      credentials: 'include',
      headers: {'Authorization': token },
    })

    if(response.ok){
      let data = await response.json()
      let id = data.chat_id
      let chats = await getAllChats(token)
      window.location.href = `/c#id=${id}`
      return chats
    }
    else{
      console.log(response)
    }

  }

  export async function deleteChat(chatId, token){

    const response = await fetch(`${PUBLIC_URL}/api/chat/delete_chat/${chatId}`,{
      method: 'DELETE',
      credentials: 'include',
      headers: {'Authorization': token },
    })

    if(response.ok){
      return "Чат удален"
    }

    else{
      console.log(response)
    }
  }