package com.atlassian.bitbucket.mesh.util;

import com.atlassian.bitbucket.mesh.rpc.v1.RpcPerson;
import com.google.protobuf.ByteString;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Objects;

import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang3.StringUtils.defaultString;

public class Person {

    private final String email;
    private final String name;

    public Person(@Nonnull RpcPerson person) {
        this.email = person.getEmail();
        this.name = person.getName().toStringUtf8();
    }

    public Person(@Nonnull String name, @Nullable String email) {
        this.email = email;
        this.name = requireNonNull(name, "name");
    }

    @Override
    public boolean equals(Object o) {
        if (o == this) {
            return true;
        }
        if (o instanceof Person) {
            Person p = (Person) o;

            return name.equals(p.name) && Objects.equals(email, p.email);
        }

        return false;
    }

    @Nonnull
    public static RpcPerson toPerson(@Nullable Person person) {
        return person == null ? RpcPerson.getDefaultInstance() : person.toPerson();
    }

    @Nullable
    public String getEmail() {
        return email;
    }

    @Nonnull
    public String getName() {
        return name;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, email);
    }

    @Nonnull
    public RpcPerson toPerson() {
        return RpcPerson.newBuilder()
                .setEmail(defaultString(email))
                .setName(ByteString.copyFromUtf8(name))
                .build();
    }
}
