package com.clevercloud.eclipse.plugin.handlers;

import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.handlers.HandlerUtil;

import com.clevercloud.eclipse.plugin.api.CcApi;
import com.clevercloud.eclipse.plugin.core.ConsoleUtils;
import com.clevercloud.eclipse.plugin.core.PreferencesUtils;
import com.clevercloud.eclipse.plugin.core.WebSocketCore;

public class LogHandler extends AbstractHandler {

	@Override
	public Object execute(ExecutionEvent event) {
		IStructuredSelection selection = (IStructuredSelection) HandlerUtil.getActiveWorkbenchWindow(event)
				.getSelectionService().getSelection();
		IProject project = (IProject) selection.getFirstElement();
		PreferencesUtils prefs = new PreferencesUtils(project, false);

		TimeZone tz = TimeZone.getTimeZone("UTC");
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:s.S'Z'");
		df.setTimeZone(tz);
		String timestamp = df.format(new Date());

		String oldlogs = CcApi.getInstance().logRequest(prefs.getId(), 300);

		try {
			URI uri = new URI("wss://logs-api.clever-cloud.com/logs-socket/" + prefs.getId() + "?since=" + timestamp);
			WebSocketCore ws = new WebSocketCore(uri, prefs.getName());
			ws.connectBlocking();
			ConsoleUtils.showConsole(prefs.getName());
			ConsoleUtils.printMessage(prefs.getName(), oldlogs);
		} catch (KeyManagementException | NoSuchAlgorithmException | URISyntaxException | InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}
}

@@ -827,16 +827,94 @@
 dler %7B%0A%0A
+%09@Override%0A%09public boolean isEnabled() %7B%0A%09%09return CcApi.isAuthentified();%0A%09%7D%0A%0A
 %09@Overri
@@ -1419,88 +1419,61 @@
 ));%0A
-%0A
 %09%09
-S
 tr
-ing oldlogs = CcApi.getInstance().logRequest(prefs.getId(), 300);%0A%0A%09%09try %7B
+y %7B%0A%09%09%09ConsoleUtils.showConsole(prefs.getName());
 %0A%09%09%09
@@ -1671,106 +1671,29 @@
 ();%0A
-%09%09%09ConsoleUtils.showConsole(prefs.getName());%0A%09%09%09ConsoleUtils.printMessage(prefs.getName(), oldlog
+%0A%09%09%09printOldLogs(pref
 s);%0A
@@ -1847,11 +1847,289 @@
 null;%0A%09%7D
+%0A%0A%09private void printOldLogs(PreferencesUtils prefs) %7B%0A%09%09String oldlogs = CcApi.getInstance().logRequest(prefs.getId(), 300);%0A%09%09String%5B%5D logs = oldlogs.split(%22%5Cn%22);%0A%09%09for (Integer i = logs.length - 1; i %3E= 0; i--) %7B%0A%09%09%09ConsoleUtils.printMessage(prefs.getName(), logs%5Bi%5D);%0A%09%09%7D%0A%09%7D
 %0A%7D%0A

check enable & old logs order