package xyz.wbsite.action.screen;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.ui.Model;
import xyz.wbsite.frame.base.Screen;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;

public class Index extends Screen {

    @Value("${file.root.path}")
    private String root;

    @Override
    public void exec(Model model, HttpServletRequest request, HttpServletResponse response) {
        String path = request.getParameter("path");
        if (path == null) {
            path = root;
        } else {
            path = root + "/" + path;
        }

        System.out.println(path);
        File rootFile = new File(path);
        if (!rootFile.exists()) {
            rootFile.mkdirs();
        }
        File[] files = rootFile.listFiles();

        model.addAttribute("files", files);
        model.addAttribute("path", new HtmlHepler().getPath(rootFile));
        model.addAttribute("html", new HtmlHepler());
    }

    public class HtmlHepler {

        public String getPath(File file) {
            if (file.getAbsolutePath().length() <= root.length()) {
                return "";
            }
            String s = file.getAbsolutePath().substring(root.length() - 1);
            s = s.replaceAll("\\\\", "/");
            return s;
        }

        public String getHtml(File file) {
            if (!file.isDirectory() || file.listFiles().length == 0) {
                return "";
            }
            StringBuilder sb = new StringBuilder();
            sb.append("<ul>");
            for (File f : file.listFiles()) {
                sb.append("<li>");
                if (f.isDirectory()) {
                    sb.append("<a class='dir' href='?path=" + getPath(f) + "'>");
                    sb.append(f.getName());
                    sb.append("</a>");
                    sb.append(getHtml(f));
                } else {
                    sb.append("<a href='download?file=" + getPath(f) + "'>");
                    sb.append(f.getName());
                    sb.append("</a>");
                }

                sb.append("</li>");
            }
            sb.append("</ul>");
            return sb.toString();
        }
    }
}
