package io.openems.edge.app.peakshaving;

import static io.openems.edge.core.appmanager.validator.Checkables.checkAppsNotInstalled;
import static io.openems.edge.core.appmanager.validator.Checkables.checkCommercial100;
import static io.openems.edge.core.appmanager.validator.Checkables.checkCommercial50Gen3;
import static io.openems.edge.core.appmanager.validator.Checkables.checkCommercial92;
import static io.openems.edge.core.appmanager.validator.Checkables.checkIndustrial;

import java.util.List;
import java.util.Map;
import java.util.function.Function;

import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;

import com.google.common.collect.Lists;
import com.google.gson.JsonElement;

import io.openems.common.exceptions.OpenemsError.OpenemsNamedException;
import io.openems.common.function.ThrowingTriFunction;
import io.openems.common.session.Language;
import io.openems.edge.app.common.props.CommonProps;
import io.openems.edge.app.common.props.ComponentProps;
import io.openems.edge.app.peakshaving.PhaseAccuratePeakShaving.Property;
import io.openems.edge.common.component.ComponentManager;
import io.openems.edge.core.appmanager.AbstractOpenemsApp;
import io.openems.edge.core.appmanager.AbstractOpenemsAppWithProps;
import io.openems.edge.core.appmanager.AppConfiguration;
import io.openems.edge.core.appmanager.AppDef;
import io.openems.edge.core.appmanager.AppDescriptor;
import io.openems.edge.core.appmanager.ComponentManagerSupplier;
import io.openems.edge.core.appmanager.ComponentUtil;
import io.openems.edge.core.appmanager.ConfigurationTarget;
import io.openems.edge.core.appmanager.Nameable;
import io.openems.edge.core.appmanager.OpenemsApp;
import io.openems.edge.core.appmanager.OpenemsAppCardinality;
import io.openems.edge.core.appmanager.OpenemsAppCategory;
import io.openems.edge.core.appmanager.Type;
import io.openems.edge.core.appmanager.Type.Parameter;
import io.openems.edge.core.appmanager.Type.Parameter.BundleParameter;
import io.openems.edge.core.appmanager.dependency.Tasks;
import io.openems.edge.core.appmanager.dependency.aggregatetask.ComponentDef;
import io.openems.edge.core.appmanager.dependency.aggregatetask.ComponentProperties;
import io.openems.edge.core.appmanager.dependency.aggregatetask.SchedulerByCentralOrderConfiguration;
import io.openems.edge.core.appmanager.validator.ValidatorConfig;

/**
 * Describes an asymmetric peak shaving app.
 *
 * <pre>
  {
    "appId":"App.PeakShaving.PeakShaving",
    "alias":"Phasengenaue Lastspitzenkappung",
    "instanceId": UUID,
    "image": base64,
    "properties":{
      "CTRL_PEAK_SHAVING_ID": "ctrlPeakShaving0",
      "ESS_ID": "ess0",
      "METER_ID":"meter0",
      "PEAK_SHAVING_POWER": 7000,
      "RECHARGE_POWER": 6000
    },
    "appDescriptor": {
    	"websiteUrl": {@link AppDescriptor#getWebsiteUrl()}
    }
  }
 * </pre>
 */
@Component(name = "App.PeakShaving.PhaseAccuratePeakShaving")
public class PhaseAccuratePeakShaving
		extends AbstractOpenemsAppWithProps<PhaseAccuratePeakShaving, Property, Parameter.BundleParameter>
		implements OpenemsApp {

	public enum Property implements Type<Property, PhaseAccuratePeakShaving, Parameter.BundleParameter>, Nameable {
		// Component-IDs
		CTRL_PEAK_SHAVING_ID(AppDef.componentId("ctrlPeakShaving0")), //
		// Properties
		ALIAS(CommonProps.alias()), //
		ESS_ID(AppDef.copyOfGeneric(ComponentProps.pickManagedSymmetricEssId(), def -> def//
				.setRequired(true)//
				.bidirectional(CTRL_PEAK_SHAVING_ID, "ess.id", //
						ComponentManagerSupplier::getComponentManager))), //
		METER_ID(AppDef.copyOfGeneric(ComponentProps.pickElectricityGridMeterId(), def -> def//
				.setRequired(true)//
				.bidirectional(CTRL_PEAK_SHAVING_ID, "meter.id", //
						ComponentManagerSupplier::getComponentManager))), //
		PEAK_SHAVING_POWER(AppDef.copyOfGeneric(PeakShavingProps.peakShavingPowerPerPhase(), def -> def//
				.setRequired(true)//
				.setAutoGenerateField(false)//
				.bidirectional(CTRL_PEAK_SHAVING_ID, "peakShavingPower", //
						ComponentManagerSupplier::getComponentManager))), //
		RECHARGE_POWER(AppDef.copyOfGeneric(PeakShavingProps.rechargePowerPerPhase(), def -> def//
				.setRequired(true)//
				.setAutoGenerateField(false)//
				.bidirectional(CTRL_PEAK_SHAVING_ID, "rechargePower", //
						ComponentManagerSupplier::getComponentManager))), //
		PEAK_SHAVING_RECHARGE_POWER_GROUP(
				PeakShavingProps.peakShavingRechargePowerGroup(PEAK_SHAVING_POWER, RECHARGE_POWER)), //
		;

		private final AppDef<? super PhaseAccuratePeakShaving, ? super Property, ? super BundleParameter> def;

		private Property(AppDef<? super PhaseAccuratePeakShaving, ? super Property, ? super BundleParameter> def) {
			this.def = def;
		}

		@Override
		public Type<Property, PhaseAccuratePeakShaving, BundleParameter> self() {
			return this;
		}

		@Override
		public AppDef<? super PhaseAccuratePeakShaving, ? super Property, ? super BundleParameter> def() {
			return this.def;
		}

		@Override
		public Function<GetParameterValues<PhaseAccuratePeakShaving>, BundleParameter> getParamter() {
			return Parameter.functionOf(AbstractOpenemsApp::getTranslationBundle);
		}

	}

	@Activate
	public PhaseAccuratePeakShaving(//
			@Reference ComponentManager componentManager, //
			ComponentContext componentContext, //
			@Reference ConfigurationAdmin cm, //
			@Reference ComponentUtil componentUtil //
	) {
		super(componentManager, componentContext, cm, componentUtil);
	}

	@Override
	public OpenemsAppCategory[] getCategories() {
		return new OpenemsAppCategory[] { OpenemsAppCategory.PEAK_SHAVING };
	}

	@Override
	public OpenemsAppCardinality getCardinality() {
		return OpenemsAppCardinality.SINGLE_IN_CATEGORY;
	}

	@Override
	protected PhaseAccuratePeakShaving getApp() {
		return this;
	}

	@Override
	protected ThrowingTriFunction<ConfigurationTarget, Map<Property, JsonElement>, Language, AppConfiguration, OpenemsNamedException> appPropertyConfigurationFactory() {
		return (t, m, l) -> {
			final var ctrlPeakShavingId = this.getId(t, m, Property.CTRL_PEAK_SHAVING_ID);

			final var alias = this.getString(m, l, Property.ALIAS);
			final var essId = this.getString(m, l, Property.ESS_ID);
			final var meterId = this.getString(m, l, Property.METER_ID);
			final var peakShavingPower = this.getInt(m, Property.PEAK_SHAVING_POWER);
			final var rechargePower = this.getInt(m, Property.RECHARGE_POWER);

			final var components = Lists.newArrayList(//
					new ComponentDef(ctrlPeakShavingId, alias, "Controller.Asymmetric.PeakShaving",
							new ComponentProperties(List.of(//
									ComponentProperties.Property.of("ess.id").withValue(essId), //
									ComponentProperties.Property.of("meter.id").withValue(meterId), //
									ComponentProperties.Property.of("peakShavingPower").withValue(peakShavingPower), //
									ComponentProperties.Property.of("rechargePower").withValue(rechargePower))), //
							ComponentDef.Configuration.defaultConfig()), //
					new ComponentDef("_power", "", "Ess.Power", new ComponentProperties(List.of(//
							ComponentProperties.Property.of("enablePid") //
									.withValue(true) //
									.withPriority(10))),
							ComponentDef.Configuration.defaultConfig()) //
			);

			return AppConfiguration.create() //
					.addTask(Tasks.componentFromComponentConfig(components)) //
					.onlyIf(t != ConfigurationTarget.VALIDATE,
							b -> b.addTask(Tasks.schedulerByCentralOrder(
									new SchedulerByCentralOrderConfiguration.SchedulerComponent(ctrlPeakShavingId,
											"Controller.Asymmetric.PeakShaving", this.getAppId()))))
					.build();
		};
	}

	@Override
	protected ValidatorConfig.Builder getValidateBuilder() {
		return ValidatorConfig.create() //
				.setCompatibleCheckableConfigs(checkIndustrial() //
						.or(checkCommercial92()) //
						.or(checkCommercial50Gen3()) //
						.or(checkCommercial100())) //
				.setInstallableCheckableConfigs(checkAppsNotInstalled("App.PeakShaving.PeakShaving",
						"App.PeakShaving.TimeSlotPeakShaving", "App.PvSelfConsumption.SelfConsumptionOptimization"));
	}

	@Override
	protected Property[] propertyValues() {
		return Property.values();
	}

}
