package com.testingtech.tci.codec;

import java.nio.charset.Charset;

import org.etsi.ttcn.tci.TciCDProvided;
import org.etsi.ttcn.tci.TciTypeClass;
import org.etsi.ttcn.tci.Type;
import org.etsi.ttcn.tci.Value;
import org.etsi.ttcn.tri.TriMessage;

import com.testingtech.ttcn.extension.CodecProvider;
import com.testingtech.ttcn.tri.AbstractCodecPlugin;
import com.testingtech.xmlschema.codec.runtime.XMLCodecPlugin;

import de.tu_berlin.cs.uebb.muttcn.runtime.RB;
import de.tu_berlin.cs.uebb.ttcn.runtime.BaseCharString;

public class RawAndXMLCodecPlugin extends AbstractCodecPlugin implements CodecProvider {

  private XMLCodecPlugin xmlCodec;

  @Override
  public boolean setUp() {
    boolean setUpResult = super.setUp();
    xmlCodec = new XMLCodecPlugin();
    xmlCodec.initAbstractPlugin(getRB());
    setUpResult |= xmlCodec.setUp();
    return setUpResult;
  }
  
  @Override
  public Value decode(TriMessage message, Type decodingHypothesis) {
    if ("Raw".equals(decodingHypothesis.getName())) {
      if (decodingHypothesis.getTypeClass() == TciTypeClass.CHARSTRING ||
          decodingHypothesis.getTypeClass() == TciTypeClass.UNIVERSAL_CHARSTRING) {
        BaseCharString string = (BaseCharString) decodingHypothesis.newInstance();
        string.setString(new String(message.getEncodedMessage(), Charset.forName("UTF-8")));
        return string;
      }
    }
    return xmlCodec.decode(message, decodingHypothesis);
  }

  @Override
  public TriMessage encode(Value value) {
    return xmlCodec.encode(value);
  }

  public TciCDProvided getCodec(RB RB, String encodingRule) {
    return new RawAndXMLCodecPlugin();
  }

}
