package ab.issue.model.values;

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.TypeConverter;
import android.arch.persistence.room.TypeConverters;
import android.support.annotation.Nullable;

import com.google.common.base.MoreObjects;
import com.google.firebase.ml.vision.barcode.FirebaseVisionBarcode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.client.result.TelParsedResult;

import java.util.List;

import javax.annotation.Nonnull;

import ab.issue.db.DbConstants;

@SuppressWarnings("Guava")
public class Phone {

    @TypeConverter
    public static String fromPhones(List<Phone> phones) {
        return new Gson().toJson(phones);
    }

    @TypeConverter
    public static List<Phone> fromPhonesJson(String phones) {
        TypeToken<List<Phone>> typeToken = new TypeToken<List<Phone>>() {
        };
        return new Gson().fromJson(phones, typeToken.getType());
    }

    public static Phone create(@Nullable FirebaseVisionBarcode.Phone phone) {
        Phone result = new Phone();
        if (phone != null) {
            result.number = phone.getNumber();
            result.phoneType = PhoneType.fromFirebasePhoneType(phone.getType());
        }
        return result;
    }

    public static Phone create(TelParsedResult telParsedResult) {
        Phone result = new Phone();
        if (telParsedResult != null) {
            result.number = telParsedResult.getNumber();
        }
        return result;
    }

    public static Phone create(String phoneNumber) {
        Phone phone = new Phone();
        phone.number = phoneNumber;
        return phone;
    }

    @TypeConverters(PhoneType.class)
    @ColumnInfo(name = DbConstants.COLUMN_NAME_PHONE_TYPE)
    private PhoneType phoneType;

    @ColumnInfo(name = DbConstants.COLUMN_NAME_PHONE_NUMBER)
    private String number;

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

    public void setNumber(String number) {
        this.number = number;
    }

    public String getNumber() {
        return number;
    }

    public PhoneType getPhoneType() {
        return phoneType;
    }

    public void setPhoneType(PhoneType phoneType) {
        this.phoneType = phoneType;
    }
}
