/*
 * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

/*
 * $Id$
 */

package com.sun.ts.tests.jsonb.customizedmapping.adapters.model.adapter;

import com.sun.ts.tests.jsonb.customizedmapping.adapters.model.Animal;
import com.sun.ts.tests.jsonb.customizedmapping.adapters.model.Cat;
import com.sun.ts.tests.jsonb.customizedmapping.adapters.model.Dog;

import javax.json.bind.adapter.JsonbAdapter;

import static com.sun.ts.tests.jsonb.customizedmapping.adapters.model.adapter.AnimalJson.TYPE.CAT;
import static com.sun.ts.tests.jsonb.customizedmapping.adapters.model.adapter.AnimalJson.TYPE.DOG;
import static com.sun.ts.tests.jsonb.customizedmapping.adapters.model.adapter.AnimalJson.TYPE.GENERIC;

public class AnimalAdapter implements JsonbAdapter<Animal, AnimalJson> {
    @Override
    public AnimalJson adaptToJson(Animal animal) throws Exception {
        AnimalJson adapted = new AnimalJson();
        if (Cat.class.isAssignableFrom(animal.getClass())) {
            adapted.setType(CAT);
            adapted.setCuddly(((Cat) animal).isCuddly());
        } else if (Dog.class.isAssignableFrom(animal.getClass())) {
            adapted.setType(DOG);
            adapted.setBarking(((Dog) animal).isBarking());
        } else {
            adapted.setType(GENERIC);
        }
        adapted.setName(animal.getName());
        adapted.setAge(animal.getAge());
        adapted.setFurry(animal.isFurry());
        adapted.setWeight(animal.getWeight());
        return adapted;
    }

    @Override
    public Animal adaptFromJson(AnimalJson adapted) throws Exception {
        Animal animal;
        switch (adapted.getType()) {
            case CAT:
                animal = new Cat();
                ((Cat) animal).setCuddly(adapted.isCuddly());
                break;
            case DOG:
                animal = new Dog();
                ((Dog) animal).setBarking(adapted.isBarking());
                break;
            default:
                animal = new Animal();
        }
        animal.setName(adapted.getName());
        animal.setAge(adapted.getAge());
        animal.setFurry(adapted.isFurry());
        animal.setWeight(adapted.getWeight());
        return animal;
    }
}
