package com.wizzardo.jrt;

import com.wizzardo.http.framework.Controller;
import com.wizzardo.http.framework.ControllerUrlMapping;
import com.wizzardo.http.framework.di.DependencyFactory;
import com.wizzardo.http.framework.template.Renderer;
import com.wizzardo.tools.collections.CollectionTools;
import com.wizzardo.tools.json.JsonTools;
import com.wizzardo.tools.security.MD5;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wizzardo on 07.12.15.
 */
public class AppController extends Controller {

    RTorrentService rtorrentService;
    ControllerUrlMapping mapping = DependencyFactory.get(ControllerUrlMapping.class);

    public Renderer index() {
        List<TorrentInfo> torrents = rtorrentService.list();
        model().append("torrents", torrents);

        Map<String, Collection<TorrentEntry>> entries = new HashMap<>();
        model().append("entries", entries);
        for (TorrentInfo torrent : torrents) {
            entries.put(torrent.getHash(), rtorrentService.entries(torrent));
        }
        return renderView("index__");
    }

    public Renderer riotIndex() {
        model().append("config", JsonTools.serialize(new CollectionTools.MapBuilder<>()
                        .add("ws", mapping.getUrlTemplate("ws").getRelativeUrl())
                        .add("addTorrent", mapping.getUrlTemplate(AppController.class, "addTorrent").getRelativeUrl())
                        .get()
        ));

        return renderView("index");
    }

    public Renderer addTorrent() {
        if (request.isMultipart()) {
            request.prepareMultiPart();

            String link = request.entry("url").asString();
            byte[] file = request.entry("file").asBytes();

            System.out.println("link: " + link);
            System.out.println("file: " + file.length + " " + MD5.create().update(file).asString());
        }

        return renderString("ok");
    }
}

@@ -282,32 +282,72 @@
 ollectionTools;%0A
+import com.wizzardo.tools.io.FileTools;%0A
 import com.wizza
@@ -413,16 +413,65 @@
 y.MD5;%0A%0A
+import java.io.File;%0Aimport java.io.IOException;%0A
 import j
@@ -1657,19 +1657,38 @@
 orrent()
+ throws IOException
  %7B%0A
-
         
@@ -1872,24 +1872,26 @@
 asBytes();%0A%0A
+//
             
@@ -1927,16 +1927,18 @@
  link);%0A
+//
         
@@ -2029,16 +2029,480 @@
 ring());
+%0A%0A            if (file.length != 0) %7B%0A                File tempFile = File.createTempFile(%22jrt%22, %22torrent%22);%0A                tempFile.deleteOnExit();%0A                FileTools.bytes(tempFile, file);%0A                rtorrentService.load(tempFile.getAbsolutePath());%0A            %7D else if (!link.isEmpty()) %7B%0A                rtorrentService.load(link);%0A            %7D else %7B%0A                throw new IllegalArgumentException(%22link and file are empty%22);%0A            %7D
 %0A       

add upload-torrent handler