package com.github.ingarabr.mi;

import java.util.ArrayList;
import java.util.Timer;

import com.yammer.dropwizard.Service;
import com.yammer.dropwizard.assets.AssetsBundle;
import com.yammer.dropwizard.config.Bootstrap;
import com.yammer.dropwizard.config.Environment;

import org.elasticsearch.client.Client;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.node.Node;
import org.elasticsearch.node.NodeBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ServerService extends Service<ServerConfiguration> {

    private static final Logger logger = LoggerFactory.getLogger(ServerService.class);

    private final Client client;
    private final ArrayList<Timer> tasks = new ArrayList<Timer>();

    public static void main(String[] args) throws Exception {
        String[] serverArgs = new String[args.length + 2];
        int i = 0;
        serverArgs[i++] = "server";
        serverArgs[i++] = "server.yml";
        for (String arg : args) {
            i++;
            serverArgs[i] = arg;
        }
        new ServerService().run(serverArgs);
    }

    public ServerService() {
        Node node = NodeBuilder.nodeBuilder().settings(ImmutableSettings.builder()).build();
        node.start();
        client = node.client();
    }

    @Override
    public void initialize(Bootstrap<ServerConfiguration> bootstrap) {
        bootstrap.setName("metric-insights");
        bootstrap.addBundle(new AssetsBundle("/assets/", "/", "index.html"));
    }

    @Override
    public void run(ServerConfiguration configuration, Environment environment) throws Exception {
        environment.addResource(new MyResource(client));

        for (ServerConfiguration.RestFetcher restFetcher : configuration.getRestFetchers()) {
            createTimer(restFetcher, configuration.getDefaultInterval());
        }
    }

    private void createTimer(ServerConfiguration.RestFetcher restFetcher, Integer defaultInterval) {
        Integer interval = restFetcher.getInterval();
        if (interval == null) {
            interval = defaultInterval;
        }

        logger.info("Creating timer task to fetch data from {} with interval {}", restFetcher.getHost(), interval);
        Timer fetcher = new Timer("fetcher", true);
        fetcher.schedule(new DataHenter(client, new RestClient(restFetcher.getHost()), restFetcher.getTags()), 1000, interval);
        tasks.add(fetcher);
    }

}

@@ -26,16 +26,44 @@
 br.mi;%0A%0A
+import java.io.IOException;%0A
 import j
@@ -82,16 +82,16 @@
 ayList;%0A
-
 import j
@@ -392,16 +392,74 @@
 ttings;%0A
+import org.elasticsearch.common.xcontent.XContentBuilder;%0A
 import o
@@ -585,16 +585,93 @@
 Factory;
+%0Aimport static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
 %0A%0Apublic
@@ -1942,24 +1942,24 @@
 tchers()) %7B%0A
-
             
@@ -2025,24 +2025,1670 @@
 );%0A        %7D
+%0A%0A        createIndex(client);%0A    %7D%0A%0A    private void createIndex(Client client) %7B%0A        String indexName = %22metrics%22;%0A        String type = %22metric%22;%0A        try %7B%0A            XContentBuilder builder = jsonBuilder()%0A                .startObject()%0A                    .startObject(type)%0A                        .startObject(%22properties%22)%0A                            .startObject(%22@timestamp%22)%0A                                .field(%22type%22, %22date%22)%0A                            .endObject()%0A                            .startObject(%22application%22)%0A                                .field(%22type%22, %22string%22)%0A                                .field(%22index%22, %22not_analyzed%22)%0A                            .endObject()%0A                            .startObject(%22environment%22)%0A                                .field(%22type%22, %22string%22)%0A                                .field(%22index%22, %22not_analyzed%22)%0A                            .endObject()%0A                            .startObject(%22host%22)%0A                                .field(%22type%22, %22string%22)%0A                                .field(%22index%22, %22not_analyzed%22)%0A                            .endObject()%0A                        .endObject()%0A                    .endObject()%0A                .endObject();%0A%0A            if (client.admin().indices().prepareExists(indexName).get().isExists()) %7B%0A                client.admin().indices().preparePutMapping(indexName).setType(type).setSource(builder).get();%0A            %7D else %7B%0A                client.admin().indices().prepareCreate(indexName).addMapping(type, builder).get();%0A            %7D%0A        %7D catch (IOException e) %7B%0A            e.printStackTrace();%0A        %7D
 %0A    %7D%0A%0A    

Put mapping upon creation.