/*
 * Copyright 2017 Adobe Systems Incorporated
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.adobe.cq.testing.client.components.foundation;

import static org.apache.http.HttpStatus.SC_OK;

import com.adobe.cq.testing.client.ComponentClient;
import org.apache.http.HttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.sling.testing.clients.ClientException;
import org.apache.sling.testing.clients.SlingHttpResponse;
import org.apache.sling.testing.clients.util.FormEntityBuilder;
import org.apache.sling.testing.clients.util.HttpUtils;
import org.apache.sling.testing.clients.util.ResourceUtil;

/**
 * Wraps the Download foundation component, providing methods for editing it. See {@code
 * /libs/foundation/components/download} in the repository for implementation details.
 */
public class Download extends AbstractFoundationComponent {

  public static final String RESOURCE_TYPE = "foundation/components/download";
  public static final String PROP_DESCRIPTION = "jcr:description";
  public static final String PROP_FILE_NAME = "fileName";
  public static final String PROP_FILE_REF = "fileReference";
  public static final String PROP_FILE = "file";
  public static final String PROP_UNDO_BLOBS = ":cq:undoblobs:";

  /**
   * The constructor stores all the component path information like parentPage, name etc.
   *
   * @param client The {@link com.adobe.cq.testing.client.FoundationClient FoundationClient} that's
   *     creating this instance.
   * @param pagePath path to the page that will contain the component.
   * @param location relative location to the parent node inside the page that will contain the
   *     component node.
   * @param nameHint name to be used for the component node. Might get altered by the server if a
   *     naming conflict occurs. The {@link #getName()} method will return the correct name after
   *     {@link #create (String,int...)} has been called.
   */
  public Download(ComponentClient client, String pagePath, String location, String nameHint) {
    super(client, pagePath, location, nameHint);
  }

  @Override
  public String getResourceType() {
    return RESOURCE_TYPE;
  }

  /**
   * Uploads the file to be used for the download component.
   *
   * @param mimeType mime type of file
   * @param fileName file name
   * @param resourcePath path to the resource
   * @param expectedStatus list of allowed HTTP Status to be returned. if not set, status 200 is
   *     assumed
   * @return a {@link SlingHttpResponse} wrapping the HTML response returned by Sling
   * @throws ClientException If something fails during request/response cycle
   */
  public SlingHttpResponse setDownload(
      String mimeType, String fileName, String resourcePath, int... expectedStatus)
      throws ClientException {

    HttpEntity entity =
        MultipartEntityBuilder.create()
            .addTextBody(PROP_FILE_NAME, fileName)
            .addBinaryBody(
                PROP_FILE,
                ResourceUtil.getResourceAsStream(resourcePath),
                ContentType.create(mimeType),
                fileName)
            .build();

    // send the request with the multipart entity as content
    return client.doPost(componentPath, entity, HttpUtils.getExpectedStatus(SC_OK, expectedStatus));
  }

  /**
   * Sets the reference to a file in the repository to be used by the download component.
   *
   * @param fileReference reference to file
   * @param fileName file name
   * @param expectedStatus list of allowed HTTP Status to be returned. if not set, status 200 is
   *     assumed
   * @return a {@link SlingHttpResponse} wrapping the HTML response returned by Sling
   * @throws ClientException If something fails during request/response cycle
   */
  public SlingHttpResponse setReference(
      String fileReference, String fileName, int... expectedStatus) throws ClientException {

    return client.doPost(
        componentPath,
        FormEntityBuilder.create()
            .addParameter("./" + PROP_FILE_REF, fileReference)
            .addParameter("./" + PROP_FILE, fileName)
            .build(),
        HttpUtils.getExpectedStatus(SC_OK, expectedStatus));
  }
}
