/*
 * Copyright © 2019 Mark Raynsford <code@io7m.com> http://io7m.com
 *
 * Permission to use, copy, modify, and/or distribute this software for
 * any purpose with or without fee is hereby granted, provided that the
 * above copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
 * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
 * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
 * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
 * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
 * SOFTWARE.
 */

package com.io7m.smfj.format.xml.internal;

import com.io7m.blackthorne.api.BTElementHandlerType;
import com.io7m.blackthorne.api.BTElementParsingContextType;
import com.io7m.smfj.core.SMFTriangles;
import com.io7m.smfj.parser.api.SMFParseErrors;
import com.io7m.smfj.parser.api.SMFParserEventsErrorType;
import java.util.Objects;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;

public final class SMFXHeaderTriangles
  implements BTElementHandlerType<Object, SMFTriangles>
{
  private final SMFTriangles.Builder builder;
  private final SMFParserEventsErrorType errors;

  public SMFXHeaderTriangles(
    final SMFParserEventsErrorType inErrors,
    final BTElementParsingContextType context)
  {
    this.errors = Objects.requireNonNull(inErrors, "errors");
    this.builder = SMFTriangles.builder();
  }

  @Override
  public void onElementStart(
    final BTElementParsingContextType context,
    final Attributes attributes)
    throws SAXException
  {
    try {
      final var count =
        Long.parseUnsignedLong(attributes.getValue("count"));
      final var sizeBits =
        Integer.parseUnsignedInt(attributes.getValue("sizeBits"));

      this.builder.setTriangleCount(count);
      this.builder.setTriangleIndexSizeBits(sizeBits);
    } catch (final Exception e) {
      throw context.parseException(e);
    }
  }

  @Override
  public SMFTriangles onElementFinished(
    final BTElementParsingContextType context)
  {
    try {
      return this.builder.build();
    } catch (final Exception e) {
      this.errors.onError(SMFParseErrors.errorException(e));
      return SMFTriangles.of(0L, 32);
    }
  }
}
