package ab.issue.model.values;

import android.arch.persistence.room.TypeConverter;

import com.google.common.base.Joiner;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.apache.commons.lang3.ArrayUtils;

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

import javax.annotation.Nonnull;

public class Address {

    @TypeConverter
    public static String fromAddresses(List<Address> addresses) {
        return new Gson().toJson(addresses);
    }

    @TypeConverter
    public static List<Address> fromAddressesJson(String addresses) {
        TypeToken<List<Address>> typeToken = new TypeToken<List<Address>>() {
        };
        return new Gson().fromJson(addresses, typeToken.getType());
    }

    public static Address create(FirebaseVisionBarcode.Address address) {
        Address result = new Address();
        if (address != null) {
            result.addressLines.addAll(Lists.newArrayList(ArrayUtils.nullToEmpty(address.getAddressLines())));
            result.location = Location.fromFirebaseAddressType(address.getType());
        }
        return result;
    }

    public static Address create(String address) {
        Address result = new Address();
        if (address != null) {
            result.addressLines.add(address);
        }
        return result;
    }

    private Location location;
    private final List<String> addressLines = new ArrayList<>();

    @Nonnull
    @Override
    public String toString() {
        return MoreObjects.toStringHelper(this)
                .add("location", location)
                .add("addressLines", addressLines)
                .omitNullValues()
                .toString();
    }

    public void setAddress(String address) {
        if (addressLines.isEmpty()) {
            addressLines.add(address);
        } else {
            addressLines.set(0, address);
        }
    }

    public Location getLocation() {
        return location;
    }

    public void setLocation(Location location) {
        this.location = location;
    }

    List<String> getAddressLines() {
        return ImmutableList.copyOf(addressLines);
    }

    String getAddressLinesSeparatedByNewLine() {
        return Joiner.on('\n').join(addressLines);
    }
}
