package cn.freemud.request.wechat.dto;

import lombok.Getter;

import java.net.MalformedURLException;
import java.net.URL;

public class SignMessageBuilder {
  private String canonicalUrl;
  @Getter
  private String nonceStr;
  @Getter
  private long timestamp = 0;
  private String httpBody;
  private String httpMethod;

  public SignMessageBuilder url(URL url) {
    this.canonicalUrl = url.getPath();
    if (url.getQuery() != null) {
      this.canonicalUrl += url.getQuery();
    }

    return this;
  }

  public SignMessageBuilder requestUrl(String requestUrl) throws MalformedURLException {
    this.url(new URL(requestUrl));

    return this;
  }

  public SignMessageBuilder canonicalUrl(String canonicalUrl) {
    this.canonicalUrl = canonicalUrl;

    return this;
  }

  public SignMessageBuilder nonceStr(String nonceStr) {
    this.nonceStr = nonceStr;

    return this;
  }

  public SignMessageBuilder timestamp(long timestamp) {
    this.timestamp = timestamp;

    return this;
  }

  public SignMessageBuilder httpBody(String httpBody) {
    this.httpBody = httpBody;

    return this;
  }

  public SignMessageBuilder httpMethod(String httpMethod) {
    this.httpMethod = httpMethod;

    return this;
  }

  public String buildMchSignMessage() {
    if (timestamp == 0) {
      throw new IllegalStateException("timestamp cannot be empty");
    }

    if (nonceStr == null) {
      throw new IllegalStateException("nonceStr cannot be empty");
    }

    if (canonicalUrl == null) {
      throw new IllegalStateException("canonicalUrl cannot be empty");
    }

    if (httpMethod == null) {
      throw new IllegalStateException("httpMethod cannot be empty");
    }

    if (httpMethod.equals("GET") && httpBody == null) {
      httpBody = "";
    }

    return httpMethod + "\n"
        + canonicalUrl + "\n"
        + timestamp + "\n"
        + nonceStr + "\n"
        + httpBody + "\n";
  }

  public String buildWechatpaySignMessage() {
    if (timestamp == 0) {
      throw new IllegalStateException("timestamp cannot be empty");
    }

    if (nonceStr == null) {
      throw new IllegalStateException("nonceStr cannot be empty");
    }

    if (httpBody == null) {
      httpBody = "";
    }

    return "" + timestamp + "\n"
        + nonceStr + "\n"
        + httpBody + "\n";
  }
}
