package com.example.cloudmusic.utils;

import androidx.annotation.NonNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OkHttpUtil {

    private final OkHttpClient client;
    private static OkHttpUtil util;

    public OkHttpUtil(){
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(20,TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS);
        client = builder.build();
    }
    public static OkHttpUtil getInstance(){
//        synchronized (OkHttpUtil.class) {
//            util = new OkHttpUtil();
//        }
        return new OkHttpUtil();
    }
    public void sendGetRequest(String url,OkhttpInterface okhttpInterface){
        Request request = new Request.Builder().url(url).build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                okhttpInterface.failure(call, e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                okhttpInterface.success(call, response);
            }
        });
    }

    public interface OkhttpInterface{
        void success(Call call,Response response);
        void failure(Call call,IOException e);
    }
}
