/*
 * Copyright 2015, TeamDev Ltd. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.spine3.sample;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spine3.base.CommandRequest;
import org.spine3.base.UserId;
import org.spine3.eventbus.EventBus;
import org.spine3.sample.order.OrderId;
import org.spine3.sample.order.OrderRepository;
import org.spine3.server.Engine;
import org.spine3.server.storage.StorageFactory;
import org.spine3.server.storage.memory.InMemoryStorageFactory;
import org.spine3.util.Users;

import javax.annotation.Nullable;
import java.util.List;

import static com.google.common.base.Strings.isNullOrEmpty;
import static org.spine3.util.Identifiers.IdConverterRegistry;
import static org.spine3.util.Identifiers.NULL_ID_OR_FIELD;

/**
 * Framework sample. To change storage implementation, see instructions under {@code storageFactory} field.
 *
 * @author Mikhail Mikhaylov
 * @author Alexander Litus
 */
@SuppressWarnings("UtilityClass")
public class Sample {

    private static final String SUCCESS_MESSAGE = "All the requests were handled.";

    // field is not final because test code injects it via setter
    @SuppressWarnings({"FieldMayBeFinal", "StaticNonFinalField"})
    private static StorageFactory storageFactory = InMemoryStorageFactory.getInstance();

    /**
     * To run the sample on a FileSystemStorageFactory, replace the above initialization with the following:
     *
     * StorageFactory storageFactory = org.spine3.server.storage.filesystem.FileSystemStorageFactory.newInstance(MySampleClass.class);
     *
     *
     * To run the sample on a LocalDatastoreStorageFactory, replace the above initialization with the following:
     *
     * StorageFactory storageFactory = org.spine3.server.storage.datastore.LocalDatastoreStorageFactory.instance();
     */

    /**
     * The entry point of the sample.
     */
    public static void main(String[] args) {

        setUp(storageFactory);

        // Generate test requests
        List<CommandRequest> requests = generateRequests();

        // Process requests
        for (CommandRequest request : requests) {
            Engine.getInstance().process(request);
        }

        log().info(SUCCESS_MESSAGE);

        tearDown(storageFactory);
    }

    /**
     * Sets up the storage, starts the engine, registers repositories, handlers etc.
     * @param storageFactory storage factory to use for storages setup and creation.
     */
    public static void setUp(StorageFactory storageFactory) {

        // Set up the storage
        storageFactory.setUp();

        // Start the engine
        Engine.start(storageFactory);

        // Register repository with the engine. This will register it in the CommandDispatcher too.
        Engine.getInstance().register(new OrderRepository());

        // Register event handlers
        EventBus.getInstance().register(new EventLogger());

        // Register id converters
        IdConverterRegistry.instance().register(OrderId.class, new OrderIdToStringConverter());
    }

    /**
     * The method to call after {@link Sample#setUp(StorageFactory)}.
     * @param storageFactory storage factory used for storages setup and creation.
     */
    public static void tearDown(StorageFactory storageFactory) {

        // Tear down storage
        storageFactory.tearDown();

        // Unregister event handlers
        EventBus.getInstance().unregister(log());

        // Stop the engine
        Engine.stop();
    }

    //TODO:2015-09-23:alexander.yevsyukov: Rename and extend sample data to better reflect the problem domain.
    // See Amazon screens for correct naming of domain things.

    private static List<CommandRequest> generateRequests() {

        List<CommandRequest> result = Lists.newArrayList();

        for (int i = 0; i < 10; i++) {

            OrderId orderId = OrderId.newBuilder().setValue(String.valueOf(i)).build();
            UserId userId = Users.createId("user_" + i);

            CommandRequest createOrder = Requests.createOrder(userId, orderId);
            CommandRequest addOrderLine = Requests.addOrderLine(userId, orderId);
            CommandRequest payForOrder = Requests.payForOrder(userId, orderId);

            result.add(createOrder);
            result.add(addOrderLine);
            result.add(payForOrder);
        }

        return result;
    }

    protected static void setStorageFactory(StorageFactory storageFactory) {
        Sample.storageFactory = storageFactory;
    }

    private Sample() {
    }

    private static Logger log() {
        return LogSingleton.INSTANCE.value;
    }

    private enum LogSingleton {
        INSTANCE;
        @SuppressWarnings("NonSerializableFieldInSerializableClass")
        private final Logger value = LoggerFactory.getLogger(Sample.class);

    }

    private static class OrderIdToStringConverter implements Function<OrderId, String> {

        @Override
        public String apply(@Nullable OrderId orderId) {

            if (orderId == null) {
                return NULL_ID_OR_FIELD;
            }

            final String value = orderId.getValue();

            if (isNullOrEmpty(value) || value.trim().isEmpty()) {
                return NULL_ID_OR_FIELD;
            }

            return value;
        }
    }
}

@@ -4306,37 +4306,8 @@
  %7B%0A%0A
-        // Tear down storage%0A
     

Remove comment.