import { HttpParams } from '@angular/common/http';

export type Parameter = HttpParams | null;

export class ParameterUtil {
  public static encode(
    parameterMap: {},
    param: {},
    extraParam?: {}
  ): Parameter {
    let parameter: HttpParams = new HttpParams();

    Object.keys(parameterMap).map(key => {
      if (!param.hasOwnProperty(key)) {
        return;
      }

      let v: any;
      if (!!extraParam && !!extraParam[key]) {
        v = extraParam[key];
      } else if (!!param[key]) {
        v = param[key];
      }

      if (!!v) {
        if (parameter.has(parameterMap[key])) {
          parameter = parameter.append(parameterMap[key], v);
        } else {
          parameter = parameter.set(parameterMap[key], v);
        }
      }
    });

    return parameter;
  }

  public static encodeFormData(
    parameterMap: {},
    param: {},
    extraParam?: {}
  ): FormData {
    const formData: FormData = new FormData();

    Object.keys(parameterMap).map(key => {
      if (!param.hasOwnProperty(key)) {
        return;
      }

      let v: any;
      if (!!extraParam && !!extraParam[key]) {
        v = extraParam[key];
      } else if (!!param[key]) {
        v = param[key];
      }

      if (!!v) {
        if (v instanceof File) {
          formData.append(parameterMap[key], v, v.name);
        } else if (Array.isArray(v)) {
          v.forEach(f => {
            formData.append(parameterMap[key], f, f.name);
          });
        } else {
          formData.append(parameterMap[key], v);
        }
      }
    });

    return formData;
  }
}
