package ru.yandex.webmaster3.core.semantic.semantic_document_parser.ogp.data;

import ru.yandex.common.util.Su;
import ru.yandex.common.util.collections.Cu;
import ru.yandex.common.util.collections.Pair;
import ru.yandex.common.util.functional.PartialFunction;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static ru.yandex.common.util.collections.CollectionFactory.pair;

/**
 * Created by IntelliJ IDEA.
 * User: rasifiel
 * Date: 8/1/11
 * Time: 4:10 PM
 * To change this template use File | Settings | File Templates.
 */
public class OGPData {

    protected final List<Pair<String, String>> data = new ArrayList<Pair<String, String>>();

    @Override
    public boolean equals(final Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final OGPData data1 = (OGPData) o;

        return data.equals(data1.data);

    }

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

    public OGPData() {
    }

    public void addData(final String prop, final String data) {
        this.data.add(pair(prop, data));
    }

    public String getFirstOrNull(final String prop) {
        for (Pair<String, String> p : data) {
            if (prop.equals(p.first)) {
                return p.second;
            }
        }
        return null;
    }

    public boolean containsProp(final String prop) {
        return getFirstOrNull(prop) != null;
    }

    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append("{\n").append(Su.join(data, ",")).append("}\n");
        return sb.toString();
    }

    public List<Pair<String, String>> getAllData() {
        return Collections.unmodifiableList(data);
    }

    private class GetDataFunction extends PartialFunction<Pair<String, String>, String> {

        private final String filteredProp;

        public GetDataFunction(final String filterdProp) {
            this.filteredProp = filterdProp;
        }

        @Override
        public String apply(final Pair<String, String> pair) {
            if (!filteredProp.equals(pair.first)) {
                throw new IllegalArgumentException("");
            } else {
                return pair.second;
            }
        }
    }

    public List<String> getData(final String field) {
        return Cu.mapWhereDefined(new GetDataFunction(field), data);
    }
}
