/**
 * This class will handle the http request that send to server. 
 * It will help debuging and handle cookie if needed.
 */

import * as Constants from "./Constans";

export class ServerHttpService{
    Get(path: string){
        let url = Constants.Server_URL + path;
        console.log("GET from: " + url);

        return fetch(url,{
            method: "GET"
        })
            .then((response) =>{
                if(response.ok){
                  return response.json();  
                }
                throw new Error("Unable to receive GET request from server with url:" + url);
            })
            .catch((reason) =>{
                console.log("Error on GET request", reason);
            }); 
    }

    Post(path: string, bodyData: any){
        let url = Constants.Server_URL + path;
        console.log("POST from: " + url);
        return fetch(url,{
            method: "POST",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(bodyData)
        })
        .then((response)=>{
            if(response.ok){
                return response.json();
            }
            throw new Error("Unable to receive POST request from server with url:" + url);
        })
        .catch((reason) =>{
            console.log("Error on POST request", reason);
        }); 
    }

    Put(path: string, bodyData: any){
        let url = Constants.Server_URL + path;
        console.log("PUT from: " + url);
        return fetch(url,{
            method: "PUT",
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(bodyData)
        })
        .then((response)=>{
            if(response.ok){
                return response.json();
            }
            throw new Error("Unable to receive PUT request from server with url:" + url);
        })
        .catch((reason) =>{
            console.log("Error on PUT request", reason);
        }); 
    }

    Delete(path:string){
        let url = Constants.Server_URL + path;
        console.log("Delete from: " + url);
        return fetch(url,{
            method: "Delete",
        })
        .then((response)=>{
            if(response.ok){
                return response.json();
            }
            throw new Error("Unable to receive DELETE request from server with url:" + url);
        })
        .catch((reason) =>{
            console.log("Error on DELETE request", reason);
        }); 
    }

}

/*
Change logs:
Date        |       Author          |   Description
2022-10-12  |    Fangzheng Zhang    |    create class and init
2022-10-17  |    Fangzheng Zhang    |    change to TS

 */