package ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.instances;

import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Node;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.data.MicroformatData;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.data.property_types.TextData;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.exceptions.EmptyMFException;
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.MFProperty;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.MFPropertyPlural;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.MFPropertyValue;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.Microformat;
import ru.yandex.webmaster3.core.semantic.semantic_document_parser.microformats.spec.property_types.TextProperty;

public class Org extends Microformat {
    final private static Org instance = new Org("org", false);
    private static MFProperty orgName;

    /**
     * the name should be equal to the header of microformat (e. g. "vcard")
     *
     * @param name
     */
    protected Org(@NotNull final String name, final boolean root) {
        super(name, root);
    }

    static {
        try {
            instance.addProperty(orgName = new MFPropertyValue("organization-name", TextProperty.getInstance()));
            instance.addProperty(new MFPropertyPlural("organization-unit", TextProperty.getInstance()));
        } catch (InvalidActionException e) {
            e.printStackTrace();
        }
        instance.freeze();
    }

    public static Org getInstance() {
        return instance;
    }

    @Override
    public boolean postProcess(@NotNull final MicroformatData data, @NotNull final String content, final Node node) throws EmptyMFException, InvalidActionException {
        if (data.isEmpty()) {
            throw new EmptyMFException(getName());
        }
        if (data.isEmpty(orgName.getName())) {
            //Implied "organization-name" Optimization
            try {
                addData(data, orgName, new TextData(content));
                return true;
            } catch (InvalidDataMFException e) {
                //e.printStackTrace();
            }
        }
        return false;
    }
}
