package org.jboss.as.console.client.shared.runtime.tx;

import com.google.gwt.event.shared.EventBus;
import com.google.inject.Inject;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.Place;
import com.gwtplatform.mvp.client.proxy.Proxy;
import org.jboss.as.console.client.core.NameTokens;
import org.jboss.as.console.client.domain.events.HostSelectionEvent;
import org.jboss.as.console.client.domain.model.SimpleCallback;
import org.jboss.as.console.client.shared.dispatch.DispatchAsync;
import org.jboss.as.console.client.shared.dispatch.impl.DMRAction;
import org.jboss.as.console.client.shared.dispatch.impl.DMRResponse;
import org.jboss.as.console.client.shared.runtime.Metric;
import org.jboss.as.console.client.shared.runtime.RuntimeBaseAddress;
import org.jboss.as.console.client.shared.state.CurrentServerSelection;
import org.jboss.as.console.client.shared.state.ServerSelectionEvent;
import org.jboss.as.console.client.shared.subsys.RevealStrategy;
import org.jboss.as.console.client.shared.subsys.tx.model.TransactionManager;
import org.jboss.as.console.client.widgets.forms.AddressBinding;
import org.jboss.as.console.client.widgets.forms.ApplicationMetaData;
import org.jboss.as.console.client.widgets.forms.EntityAdapter;
import org.jboss.dmr.client.ModelNode;

import java.util.Random;

import static org.jboss.dmr.client.ModelDescriptionConstants.*;

/**
 * @author Heiko Braun
 * @date 11/3/11
 */
public class TXMetricPresenter extends Presenter<TXMetricPresenter.MyView, TXMetricPresenter.MyProxy>
        implements TXMetricManagement , ServerSelectionEvent.ServerSelectionListener{

    private DispatchAsync dispatcher;
    private AddressBinding addressBinding;
    private EntityAdapter<TransactionManager> entityAdapter;
    private RevealStrategy revealStrategy;
    private CurrentServerSelection serverSelection;

    @ProxyCodeSplit
    @NameToken(NameTokens.TXMetrics)
    public interface MyProxy extends Proxy<TXMetricPresenter>, Place {
    }

    public interface MyView extends TXMetricView  {
        void setPresenter(TXMetricManagement presenter);
        void setTxMetric(Metric txMetric);
        void setRollbackMetric(Metric rollbackMetric);

        void clearSamples();
    }

    @Inject
    public TXMetricPresenter(
            EventBus eventBus, MyView view, MyProxy proxy,
            DispatchAsync dispatcher,
            ApplicationMetaData metaData, RevealStrategy revealStrategy,
            CurrentServerSelection serverSelection) {
        super(eventBus, view, proxy);

        this.dispatcher = dispatcher;
        this.revealStrategy = revealStrategy;
        this.serverSelection = serverSelection;

        this.addressBinding = metaData.getBeanMetaData(TransactionManager.class).getAddress();
        this.entityAdapter = new EntityAdapter<TransactionManager>(TransactionManager.class, metaData);
    }

    @Override
    public void onServerSelection(String hostName, String serverName) {

        getView().clearSamples();

        // refresh if needed. Otherwise it will happen onReset()
        if(isVisible()) refresh();
    }

    @Override
    protected void onBind() {
        super.onBind();
        getView().setPresenter(this);
        getEventBus().addHandler(ServerSelectionEvent.TYPE, this);
    }

    @Override
    protected void onReset() {
        super.onReset();
        refresh();
    }

    @Override
    protected void revealInParent() {
        revealStrategy.revealInRuntimeParent(this);
    }


    @Override
    public void refresh() {

        ModelNode operation = addressBinding.asResource(RuntimeBaseAddress.get());
        operation.get(OP).set(READ_RESOURCE_OPERATION);
        operation.get(INCLUDE_RUNTIME).set(true);

        dispatcher.execute(new DMRAction(operation), new SimpleCallback<DMRResponse>() {
            @Override
            public void onSuccess(DMRResponse dmrResponse) {
                ModelNode result = ModelNode.fromBase64(dmrResponse.getResponseText());

                TransactionManager metrics = entityAdapter.fromDMR(result.get(RESULT));

                getView().setTxMetric(new Metric(
                        metrics.getNumTransactions(),
                        metrics.getNumCommittedTransactions(),
                        metrics.getNumAbortedTransactions(),
                        metrics.getNumTimeoutTransactions()
                        ));

                getView().setRollbackMetric(new Metric(
                        metrics.getNumApplicationRollback(),
                        metrics.getNumResourceRollback()
                ));


                //provideRandomMetrics();

            }
        });
    }

    // TODO: remove at some point
    private void provideRandomMetrics() {

        final Random random = new Random(System.currentTimeMillis());

        int total = 175;
        int committed = random.nextInt(50);

        getView().setTxMetric(new Metric(
                total,
                committed,
                total-committed,
                0L));

        getView().setRollbackMetric(new Metric(
                        (long)random.nextInt(50),
                        (long)random.nextInt(75)
                ));
    }
}

@@ -441,77 +441,8 @@
 ns;%0A
-import org.jboss.as.console.client.domain.events.HostSelectionEvent;%0A
 impo
@@ -501,16 +501,16 @@
 llback;%0A
+
 import o
@@ -2263,17 +2263,16 @@
 etric);%0A
-%0A
         
@@ -3559,17 +3559,16 @@
 %0A    %7D%0A%0A
-%0A
     @Ove
@@ -4735,545 +4735,6 @@
  %7D%0A%0A
-    // TODO: remove at some point%0A    private void provideRandomMetrics() %7B%0A%0A        final Random random = new Random(System.currentTimeMillis());%0A%0A        int total = 175;%0A        int committed = random.nextInt(50);%0A%0A        getView().setTxMetric(new Metric(%0A                total,%0A                committed,%0A                total-committed,%0A                0L));%0A%0A        getView().setRollbackMetric(new Metric(%0A                        (long)random.nextInt(50),%0A                        (long)random.nextInt(75)%0A                ));%0A    %7D%0A
 %7D%0A

remove mock data methods