package org.eclipse.steady.kb.task;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import org.apache.commons.io.FileUtils;
import org.eclipse.steady.backend.BackendConnectionException;
import org.eclipse.steady.core.util.CoreConfiguration;
import org.eclipse.steady.kb.ZipUtil;
import org.eclipse.steady.kb.model.Vulnerability;
import org.eclipse.steady.kb.util.ConstructSet;
import org.eclipse.steady.kb.util.Metadata;
import org.eclipse.steady.shared.json.model.Bug;
import org.eclipse.steady.shared.util.VulasConfiguration;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Test;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.JsonSyntaxException;

public class TestImportVulnerability_CVE_2017_2617 {

  private static final String ZIP = "CVE-2017-2617.zip";
  private static final String REPO = "CVE-2017-2617";
  private static String destPathToUnzip = System.getProperty("java.io.tmpdir");

  @Before
  public void setup() {
    String path = ConstructSet.class.getClassLoader().getResource(ZIP).getPath();
    if (!destPathToUnzip.endsWith(File.separator)) {
      destPathToUnzip = destPathToUnzip + File.separator;
    }

    ZipUtil.unzip(path, destPathToUnzip);
  }

  @Test
  public void testImportVuln() throws JsonSyntaxException, IOException, BackendConnectionException {
    VulasConfiguration.getGlobal()
        .setProperty(
            CoreConfiguration.BACKEND_CONNECT,
            (CoreConfiguration.ConnectType.READ_WRITE.toString()));
    Vulnerability vuln = Metadata.getVulnerabilityMetadata(destPathToUnzip + REPO);
    MockBackConnector mockBackendConnector = new MockBackConnector();
    HashMap<String, Object> args = new HashMap<String, Object>();
    args.put("d", destPathToUnzip + File.separator + REPO);
    args.put("o", false);
    args.put("v", false);
    ImportVulnerability importVuln = new ImportVulnerability();
    importVuln.execute(vuln, args, mockBackendConnector);
    ObjectMapper mapper = new ObjectMapper();
    Bug bug = mapper.readValue(mockBackendConnector.getUploadJson(), Bug.class);
    assertEquals("CVE-2017-2617", bug.getBugId());
    assertNotNull(bug.getDescription());
  }

  @AfterClass
  public static void cleanup() {
    try {
      FileUtils.deleteDirectory(new File(destPathToUnzip + REPO));
    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}
