package com.xunmei.common.core.http.service.params;


import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import okhttp3.Request;
import org.apache.commons.lang3.StringUtils;

import java.util.Collections;
import java.util.Map;
import java.util.TreeMap;

/**
 * Tkk
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public abstract class HttpParams {

    /**
     * @param url
     * @return
     */
    public static HttpParams get(final String url) {
        return new HttpParamsGet(url, Collections.emptyMap());
    }

    /**
     * @param url
     * @return
     */
    public static HttpParams get(final String url, final Map<String, Object> params) {
        return new HttpParamsGet(url, params);
    }

    /**
     * @param url
     * @return
     */
    public static HttpParams post(final String url, final Map<String, Object> params) {
        return new HttpParamsPost(url, params);
    }

    /**
     * @param url
     * @return
     */
    public static HttpParams postFile(final String url, final Map<String, Object> params) {
        return new HttpParamsPostFile(url, params);
    }

    /**
     * @param url
     * @return
     */
    public static HttpParams postJson(final String url, final Object params) {
        return new HttpParamsPostJson(url, params);
    }


    private String url;

    private String userAgent;

    private Map<String, String> heads;

    public Request toRequest() {
        final Request.Builder request = this.toBuild();
        if (StringUtils.isNotBlank(this.userAgent)) {
            request.addHeader("User-Agent", this.userAgent);
        }
        if (this.heads != null) {
            this.heads.forEach(request::addHeader);
        }
        return request.build();
    }

    public HttpParams putHead(final String k, final String v) {
        if (this.heads == null) {
            this.heads = new TreeMap<>();
        }
        this.heads.put(k, v);
        return this;
    }

    protected abstract Request.Builder toBuild();

    public abstract HttpParams put(final String key, final Object page);

    @Override
    public String toString() {
        return this.url;
    }
}


