package ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.data.property_types;

import org.jetbrains.annotations.NotNull;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.data.MFAnyData;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.exceptions.InvalidActionException;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.exceptions.InvalidDataMFException;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.MFType;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.property_types.TelURIProperty;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 10/5/11
 * Time: 10:31 PM
 * To change this template use File | Settings | File Templates.
 */
public class TelURIData extends MFAnyData implements Concatenable {

    @NotNull
    public String uri;

    public TelURIData() {
        uri = "";
    }

    public TelURIData(@NotNull final String uri) {
        this();
        this.uri = optimize(uri.trim());
    }

    private String optimize(final String uri) {
        if (uri.startsWith("tel:"))
            return uri.substring("tel:".length());
        if (uri.startsWith("wtai://wp/mc;"))
            try {
                return URLDecoder.decode(uri.substring("wtai://wp/mc;".length()), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                //Can't be
                throw new RuntimeException("UTF-8 is not supported O_O");
            }
        return uri;
    }

    @Override
    public String toString() {
        return uri;
    }

    @Override
    public MFType getSpec() {
        return TelURIProperty.getInstance();
    }

    @Override
    public boolean isEmpty() {
        return uri.isEmpty();
    }

    @Override
    public TelURIData clone() {
        return new TelURIData(uri);
    }

    @Override
    public String toShortString() {
        try {
            return getSpec().toShortString(this);
        } catch (InvalidActionException e) {
            e.printStackTrace();  //cannot be
            return null;
        }
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof TelURIData)) {
            return false;
        }

        final TelURIData uriData = (TelURIData) o;

        return uri.equalsIgnoreCase(uriData.uri);

    }

    @Override
    public int hashCode() {
        return uri.toLowerCase().hashCode();
    }

    @Override
    public void append(final MFAnyData second) throws InvalidDataMFException {
        if (second instanceof TelURIData || second instanceof TextData) {
            uri = uri+second.toString();
        } else {
            throw new InvalidDataMFException("tel");
        }
    }
}
