/*
 * Licensed Materials - Property of Perforce Software, Inc. 
 * © Copyright Perforce Software, Inc. 2014, 2021 
 * © Copyright IBM Corp. 2009, 2014
 * © Copyright ILOG 1996, 2009
 * All Rights Reserved.
 *
 * Note to U.S. Government Users Restricted Rights:
 * The Software and Documentation were developed at private expense and
 * are "Commercial Items" as that term is defined at 48 CFR 2.101,
 * consisting of "Commercial Computer Software" and
 * "Commercial Computer Software Documentation", as such terms are
 * used in 48 CFR 12.212 or 48 CFR 227.7202-1 through 227.7202-4,
 * as applicable.
 */

import java.io.IOException;

import ilog.views.IlvGraphic;
import ilog.views.graphic.IlvText;
import ilog.views.io.IlvInputStream;
import ilog.views.io.IlvOutputStream;
import ilog.views.io.IlvPersistentObject;
import ilog.views.io.IlvReadFileException;
import ilog.views.java2d.IlvBlinkingAction;

/**
 * A persistent blinking action that can be saved into IVL files.
 * It switches between two labels of an IlvText. 
 */
public class LabelBlinkingAction extends IlvBlinkingAction
                                 implements IlvPersistentObject
{
  private String label1;
  private String label2;

  /**
   * Creates the blinking action.
   */
  public LabelBlinkingAction(long onPeriod, long offPeriod,
                             String label1, String label2)
  {
    super(onPeriod, offPeriod);
    this.label1 = label1;
    this.label2 = label2;
  }

  /**
   * Creates the blinking action from an input stream.
   */
  public LabelBlinkingAction(IlvInputStream stream) throws IlvReadFileException
  {
    this(readPeriods(stream));
    label1 = stream.readString("label1");
    label2 = stream.readString("label2");
  }

  /**
   * Creates the blinking action.
   * Only needed to simplify the stream constructor.
   */
  private LabelBlinkingAction(long[] periods)
  {
    super(periods[0], periods[1]);
  }

  /**
   * Utility to read the "on" and "off" period.
   */
  private static long[] readPeriods(IlvInputStream stream)
    throws IlvReadFileException
  {
    long[] result = new long[2];
    result[0] = stream.readLong("onPeriod");
    result[1] = stream.readLong("offPeriod");
    return result;
  }

  /**
   * Writes the blinking action to a stream.
   */
  Override
  public void write(IlvOutputStream stream) throws IOException
  {
    stream.write("onPeriod", getOnPeriod());
    stream.write("offPeriod", getOffPeriod());
    stream.write("label1", label1);
    stream.write("label2", label2);
  }

  /**
   * Changes the state of an IlvText during blinking.
   */
  Override
  protected void changeState(IlvGraphic obj, boolean isOn)
  {
    // no applyToObject necessary because the caller does it already for us
    IlvText text = (IlvText)obj;
    if (isOn) {
      text.setLabel(label1);
    } else {
      text.setLabel(label2);
    }
  }
}