/*
 * Copyright (C) 2016 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.strata.product.credit.type;

import java.io.Serializable;
import java.time.LocalDate;
import java.util.Map;
import java.util.NoSuchElementException;

import org.joda.beans.Bean;
import org.joda.beans.BeanBuilder;
import org.joda.beans.ImmutableBean;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaBean;
import org.joda.beans.MetaProperty;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.PropertyDefinition;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import org.joda.beans.impl.direct.DirectPrivateBeanBuilder;

import com.opengamma.strata.basics.ReferenceData;
import com.opengamma.strata.basics.StandardId;
import com.opengamma.strata.basics.currency.AdjustablePayment;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.product.common.BuySell;
import com.opengamma.strata.product.credit.CdsTrade;

/**
 * A template for creating credit default swap trades.
 * <p>
 * This defines almost all the data necessary to create a credit default swap {@link CdsTrade}.
 * The start and end of the trade are specified by {@code LocalDate}.
 * Use {@link TenorCdsTemplate} for standard CDS trades.
 * <p>
 * The legal entity ID, trade date, notional and fixed rate are required to complete the template and create the trade.
 * As such, it is often possible to get a market quote for a trade based on the template.
 * <p>
 * A CDS is quoted in points upfront, par spread, or quoted spread. 
 * For the latter two cases, the market quotes are passed as the fixed rate.
 */
@BeanDefinition(builderScope = "private")
public final class DatesCdsTemplate
    implements CdsTemplate, ImmutableBean, Serializable {

  /**
   * The start date.
   * <p>
   * The start date of the underling CDS product.
   * This date can be modified following the rule in {@code convention}. 
   */
  @PropertyDefinition(validate = "notNull")
  private final LocalDate startDate;
  /**
   * The end date.
   * <p>
   * The end date of the underling CDS product.
   * This date can be modified following the rule in {@code convention}. 
   */
  @PropertyDefinition(validate = "notNull")
  private final LocalDate endDate;
  /**
  * The market convention of the credit default swap.
  */
  @PropertyDefinition(validate = "notNull", overrideGet = true)
  private final CdsConvention convention;

  //-------------------------------------------------------------------------
  /**
   * Obtains a template based on the specified dates and convention.
   * 
   * @param startDate  the start date
   * @param endDate  the end date
   * @param convention  the convention
   * @return the template
   */
  public static DatesCdsTemplate of(LocalDate startDate, LocalDate endDate, CdsConvention convention) {
    ArgChecker.inOrderNotEqual(startDate, endDate, "startDate", "endDate");
    return new DatesCdsTemplate(startDate, endDate, convention);
  }

  //-------------------------------------------------------------------------
  @Override
  public CdsTrade createTrade(
      StandardId legalEntityId,
      LocalDate tradeDate,
      BuySell buySell,
      double notional,
      double fixedRate,
      ReferenceData refData) {

    ArgChecker.inOrderNotEqual(tradeDate, endDate, "tradeDate", "endDate");
    return convention.createTrade(legalEntityId, tradeDate, startDate, endDate, buySell, notional, fixedRate, refData);
  }

  @Override
  public CdsTrade createTrade(
      StandardId legalEntityId,
      LocalDate tradeDate,
      BuySell buySell,
      double notional,
      double fixedRate,
      AdjustablePayment upFrontFee,
      ReferenceData refData) {

    ArgChecker.inOrderNotEqual(tradeDate, endDate, "tradeDate", "endDate");
    return convention.createTrade(
        legalEntityId, tradeDate, startDate, endDate, buySell, notional, fixedRate, upFrontFee, refData);
  }

  //------------------------- AUTOGENERATED START -------------------------
  /**
   * The meta-bean for {@code DatesCdsTemplate}.
   * @return the meta-bean, not null
   */
  public static DatesCdsTemplate.Meta meta() {
    return DatesCdsTemplate.Meta.INSTANCE;
  }

  static {
    MetaBean.register(DatesCdsTemplate.Meta.INSTANCE);
  }

  /**
   * The serialization version id.
   */
  private static final long serialVersionUID = 1L;

  private DatesCdsTemplate(
      LocalDate startDate,
      LocalDate endDate,
      CdsConvention convention) {
    JodaBeanUtils.notNull(startDate, "startDate");
    JodaBeanUtils.notNull(endDate, "endDate");
    JodaBeanUtils.notNull(convention, "convention");
    this.startDate = startDate;
    this.endDate = endDate;
    this.convention = convention;
  }

  @Override
  public DatesCdsTemplate.Meta metaBean() {
    return DatesCdsTemplate.Meta.INSTANCE;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the start date.
   * <p>
   * The start date of the underling CDS product.
   * This date can be modified following the rule in {@code convention}.
   * @return the value of the property, not null
   */
  public LocalDate getStartDate() {
    return startDate;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the end date.
   * <p>
   * The end date of the underling CDS product.
   * This date can be modified following the rule in {@code convention}.
   * @return the value of the property, not null
   */
  public LocalDate getEndDate() {
    return endDate;
  }

  //-----------------------------------------------------------------------
  /**
   * Gets the market convention of the credit default swap.
   * @return the value of the property, not null
   */
  @Override
  public CdsConvention getConvention() {
    return convention;
  }

  //-----------------------------------------------------------------------
  @Override
  public boolean equals(Object obj) {
    if (obj == this) {
      return true;
    }
    if (obj != null && obj.getClass() == this.getClass()) {
      DatesCdsTemplate other = (DatesCdsTemplate) obj;
      return JodaBeanUtils.equal(startDate, other.startDate) &&
          JodaBeanUtils.equal(endDate, other.endDate) &&
          JodaBeanUtils.equal(convention, other.convention);
    }
    return false;
  }

  @Override
  public int hashCode() {
    int hash = getClass().hashCode();
    hash = hash * 31 + JodaBeanUtils.hashCode(startDate);
    hash = hash * 31 + JodaBeanUtils.hashCode(endDate);
    hash = hash * 31 + JodaBeanUtils.hashCode(convention);
    return hash;
  }

  @Override
  public String toString() {
    StringBuilder buf = new StringBuilder(128);
    buf.append("DatesCdsTemplate{");
    buf.append("startDate").append('=').append(JodaBeanUtils.toString(startDate)).append(',').append(' ');
    buf.append("endDate").append('=').append(JodaBeanUtils.toString(endDate)).append(',').append(' ');
    buf.append("convention").append('=').append(JodaBeanUtils.toString(convention));
    buf.append('}');
    return buf.toString();
  }

  //-----------------------------------------------------------------------
  /**
   * The meta-bean for {@code DatesCdsTemplate}.
   */
  public static final class Meta extends DirectMetaBean {
    /**
     * The singleton instance of the meta-bean.
     */
    static final Meta INSTANCE = new Meta();

    /**
     * The meta-property for the {@code startDate} property.
     */
    private final MetaProperty<LocalDate> startDate = DirectMetaProperty.ofImmutable(
        this, "startDate", DatesCdsTemplate.class, LocalDate.class);
    /**
     * The meta-property for the {@code endDate} property.
     */
    private final MetaProperty<LocalDate> endDate = DirectMetaProperty.ofImmutable(
        this, "endDate", DatesCdsTemplate.class, LocalDate.class);
    /**
     * The meta-property for the {@code convention} property.
     */
    private final MetaProperty<CdsConvention> convention = DirectMetaProperty.ofImmutable(
        this, "convention", DatesCdsTemplate.class, CdsConvention.class);
    /**
     * The meta-properties.
     */
    private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
        this, null,
        "startDate",
        "endDate",
        "convention");

    /**
     * Restricted constructor.
     */
    private Meta() {
    }

    @Override
    protected MetaProperty<?> metaPropertyGet(String propertyName) {
      switch (propertyName.hashCode()) {
        case -2129778896:  // startDate
          return startDate;
        case -1607727319:  // endDate
          return endDate;
        case 2039569265:  // convention
          return convention;
      }
      return super.metaPropertyGet(propertyName);
    }

    @Override
    public BeanBuilder<? extends DatesCdsTemplate> builder() {
      return new DatesCdsTemplate.Builder();
    }

    @Override
    public Class<? extends DatesCdsTemplate> beanType() {
      return DatesCdsTemplate.class;
    }

    @Override
    public Map<String, MetaProperty<?>> metaPropertyMap() {
      return metaPropertyMap$;
    }

    //-----------------------------------------------------------------------
    /**
     * The meta-property for the {@code startDate} property.
     * @return the meta-property, not null
     */
    public MetaProperty<LocalDate> startDate() {
      return startDate;
    }

    /**
     * The meta-property for the {@code endDate} property.
     * @return the meta-property, not null
     */
    public MetaProperty<LocalDate> endDate() {
      return endDate;
    }

    /**
     * The meta-property for the {@code convention} property.
     * @return the meta-property, not null
     */
    public MetaProperty<CdsConvention> convention() {
      return convention;
    }

    //-----------------------------------------------------------------------
    @Override
    protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
      switch (propertyName.hashCode()) {
        case -2129778896:  // startDate
          return ((DatesCdsTemplate) bean).getStartDate();
        case -1607727319:  // endDate
          return ((DatesCdsTemplate) bean).getEndDate();
        case 2039569265:  // convention
          return ((DatesCdsTemplate) bean).getConvention();
      }
      return super.propertyGet(bean, propertyName, quiet);
    }

    @Override
    protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
      metaProperty(propertyName);
      if (quiet) {
        return;
      }
      throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
    }

  }

  //-----------------------------------------------------------------------
  /**
   * The bean-builder for {@code DatesCdsTemplate}.
   */
  private static final class Builder extends DirectPrivateBeanBuilder<DatesCdsTemplate> {

    private LocalDate startDate;
    private LocalDate endDate;
    private CdsConvention convention;

    /**
     * Restricted constructor.
     */
    private Builder() {
    }

    //-----------------------------------------------------------------------
    @Override
    public Object get(String propertyName) {
      switch (propertyName.hashCode()) {
        case -2129778896:  // startDate
          return startDate;
        case -1607727319:  // endDate
          return endDate;
        case 2039569265:  // convention
          return convention;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
    }

    @Override
    public Builder set(String propertyName, Object newValue) {
      switch (propertyName.hashCode()) {
        case -2129778896:  // startDate
          this.startDate = (LocalDate) newValue;
          break;
        case -1607727319:  // endDate
          this.endDate = (LocalDate) newValue;
          break;
        case 2039569265:  // convention
          this.convention = (CdsConvention) newValue;
          break;
        default:
          throw new NoSuchElementException("Unknown property: " + propertyName);
      }
      return this;
    }

    @Override
    public DatesCdsTemplate build() {
      return new DatesCdsTemplate(
          startDate,
          endDate,
          convention);
    }

    //-----------------------------------------------------------------------
    @Override
    public String toString() {
      StringBuilder buf = new StringBuilder(128);
      buf.append("DatesCdsTemplate.Builder{");
      buf.append("startDate").append('=').append(JodaBeanUtils.toString(startDate)).append(',').append(' ');
      buf.append("endDate").append('=').append(JodaBeanUtils.toString(endDate)).append(',').append(' ');
      buf.append("convention").append('=').append(JodaBeanUtils.toString(convention));
      buf.append('}');
      return buf.toString();
    }

  }

  //-------------------------- AUTOGENERATED END --------------------------

}
