package ca.uhn.fhir.cli;

/*-
 * #%L
 * HAPI FHIR - Command Line Client - API
 * %%
 * Copyright (C) 2014 - 2019 University Health Network
 * %%
 * 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.
 * #L%
 */

import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jpa.term.IHapiTerminologyLoaderSvc;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.util.ParametersUtil;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.hl7.fhir.instance.model.api.IBaseParameters;
import org.hl7.fhir.r4.model.CodeSystem;

import static org.apache.commons.lang3.StringUtils.isBlank;

public class UploadTerminologyCommand extends BaseCommand {
	// TODO: Don't use qualified names for loggers in HAPI CLI.
	private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UploadTerminologyCommand.class);
	private static final String UPLOAD_EXTERNAL_CODE_SYSTEM = "upload-external-code-system";

	@Override
	public String getCommandDescription() {
		return "Uploads a terminology package (e.g. a SNOMED CT ZIP file) to a server, using the $" + UPLOAD_EXTERNAL_CODE_SYSTEM + " operation.";
	}

	@Override
	public String getCommandName() {
		return "upload-terminology";
	}

	@Override
	public Options getOptions() {
		Options options = new Options();

		addFhirVersionOption(options);
		addBaseUrlOption(options);
		addRequiredOption(options, "u", "url", true, "The code system URL associated with this upload (e.g. " + IHapiTerminologyLoaderSvc.SCT_URI + ")");
		addOptionalOption(options, "d", "data", true, "Local file to use to upload (can be a raw file or a ZIP containing the raw file)");
		addOptionalOption(options, null, "custom", false, "Indicates that this upload uses the HAPI FHIR custom external terminology format");
		addBasicAuthOption(options);
		addVerboseLoggingOption(options);

		return options;
	}

	@Override
	public void run(CommandLine theCommandLine) throws ParseException {
		parseFhirContext(theCommandLine);
		FhirContext ctx = getFhirContext();

		String termUrl = theCommandLine.getOptionValue("u");
		if (isBlank(termUrl)) {
			throw new ParseException("No URL provided");
		}

		String[] datafile = theCommandLine.getOptionValues("d");
		if (datafile == null || datafile.length == 0) {
			throw new ParseException("No data file provided");
		}

		IGenericClient client = super.newClient(theCommandLine);
		IBaseParameters inputParameters = ParametersUtil.newInstance(myFhirCtx);
		ParametersUtil.addParameterToParametersUri(myFhirCtx, inputParameters, "url", termUrl);
		for (String next : datafile) {
			ParametersUtil.addParameterToParametersString(myFhirCtx, inputParameters, "localfile", next);
		}
		if (theCommandLine.hasOption("custom")) {
			ParametersUtil.addParameterToParametersCode(myFhirCtx, inputParameters, "contentMode", "custom");
		}

		if (theCommandLine.hasOption(VERBOSE_LOGGING_PARAM)) {
			client.registerInterceptor(new LoggingInterceptor(true));
		}

		ourLog.info("Beginning upload - This may take a while...");

		IBaseParameters response;
		switch (myFhirCtx.getVersion().getVersion()) {
			case DSTU3:
				response = client
					.operation()
					.onType(org.hl7.fhir.dstu3.model.CodeSystem.class)
					.named(UPLOAD_EXTERNAL_CODE_SYSTEM)
					.withParameters(inputParameters)
					.execute();
				break;
			case R4:
				response = client
					.operation()
					.onType(CodeSystem.class)
					.named(UPLOAD_EXTERNAL_CODE_SYSTEM)
					.withParameters(inputParameters)
					.execute();
				break;
			default:
				throw new UnsupportedOperationException("This command does not currently support " + myFhirCtx.getVersion().getVersion());
		}

		ourLog.info("Upload complete!");
		ourLog.info("Response:\n{}", ctx.newXmlParser().setPrettyPrint(true).encodeResourceToString(response));
	}

}

@@ -710,48 +710,8 @@
 */%0A%0A
-import ca.uhn.fhir.context.FhirContext;%0A
 impo
@@ -1102,49 +1102,8 @@
 ers;
-%0Aimport org.hl7.fhir.r4.model.CodeSystem;
 %0A%0Aim
@@ -2532,46 +2532,8 @@
 ne);
-%0A%09%09FhirContext ctx = getFhirContext();
 %0A%0A%09%09
@@ -3548,86 +3548,8 @@
 ers 
-response;%0A%09%09switch (myFhirCtx.getVersion().getVersion()) %7B%0A%09%09%09case DSTU3:%0A%09%09%09%09
 resp
@@ -3557,34 +3557,32 @@
 nse = client%0A%09%09%09
-%09
-%09
 .operation()%0A%09%09%09
@@ -3581,26 +3581,24 @@
 on()%0A%09%09%09
-%09%09
 .onType(
 org.hl7.
@@ -3593,243 +3593,78 @@
 ype(
-org.hl7.fhir.dstu3.model.CodeSystem.class)%0A%09%09%09%09%09.named(UPLOAD_EXTERNAL_CODE_SYSTEM)%0A%09%09%09%09%09.withParameters(inputParameters)%0A%09%09%09%09%09.execute();%0A%09%09%09%09break;%0A%09%09%09case R4:%0A%09%09%09%09response = client%0A%09%09%09%09%09.operation()%0A%09%09%09%09%09.onType(CodeSystem.class)%0A%09%09
+myFhirCtx.getResourceDefinition(%22CodeSystem%22).getImplementingClass())%0A
 %09%09%09.
@@ -3701,18 +3701,16 @@
 TEM)%0A%09%09%09
-%09%09
 .withPar
@@ -3734,18 +3734,16 @@
 meters)%0A
-%09%09
 %09%09%09.exec
@@ -3752,162 +3752,8 @@
 e();
-%0A%09%09%09%09break;%0A%09%09%09default:%0A%09%09%09%09throw new UnsupportedOperationException(%22This command does not currently support %22 + myFhirCtx.getVersion().getVersion());%0A%09%09%7D
 %0A%0A%09%09
@@ -3816,17 +3816,23 @@
 :%5Cn%7B%7D%22, 
-c
+myFhirC
 tx.newXm

Address review comments.