package org.popkit.leap.elpa.controller;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.popkit.core.entity.CommonResponse;
import org.popkit.core.entity.SimpleResult;
import org.popkit.leap.elpa.entity.ActorStatus;
import org.popkit.leap.elpa.entity.ArchiveVo;
import org.popkit.leap.elpa.entity.RecipeDo;
import org.popkit.leap.elpa.services.*;
import org.popkit.leap.elpa.utils.PelpaUtils;
import org.popkit.leap.elpa.utils.RecipeParser;
import org.popkit.leap.monitor.EachActor;
import org.popkit.leap.monitor.RoundMonitor;
import org.popkit.leap.monitor.RoundSupervisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Aborn Jiang
 * Mail aborn.jiang@gmail.com
 * 2016-05-14:06:57
 */
@Controller
@RequestMapping(value = "elpa")
public class ElpaController {

    @Autowired
    private PkgFetchService pkgFetchService;

    @Autowired
    private RecipesService recipesService;

    @Autowired
    private PkgBuildService pkgBuildService;

    @Autowired
    private ArchiveContentsGenerator archiveContentsGenerator;

    @RequestMapping(value = "index.html")
    public String index(HttpServletRequest request) {
        Map<String, EachActor> actorMap = RoundMonitor.getActors();
        List<EachActor> unstarted = new ArrayList<EachActor>();
        List<EachActor> finished = new ArrayList<EachActor>();
        List<EachActor> onging = new ArrayList<EachActor>();

        int unstartedNo = 0;
        int finishedNo = 0;
        int ongingNo = 0;
        List<String> pkgReady = new ArrayList<String>();
        List<String> pkgFinished = new ArrayList<String>();
        List<String> pkgOnging = new ArrayList<String>();

        if (MapUtils.isNotEmpty(actorMap)) {
            for (String pkg : actorMap.keySet()) {
                EachActor actor = actorMap.get(pkg);
                if (actor.getBuildStatus() == ActorStatus.READY) {
                    if (unstartedNo < 50) {
                        unstarted.add(actor);
                        unstartedNo++;
                    }
                    pkgReady.add(pkg);
                } else if (actor.getBuildStatus() == ActorStatus.WORKING) {
                    if (ongingNo < 50) {
                        onging.add(actor);
                        ongingNo++;
                    }
                    pkgOnging.add(pkg);
                } else if (actor.getBuildStatus() == ActorStatus.FINISHED) {
                    if (finishedNo < 50) {
                        finished.add(actor);
                        finishedNo++;
                    }
                    pkgFinished.add(pkg);
                }
            }
        }

        request.setAttribute("percent", RoundMonitor.finishedPercent());

        request.setAttribute("pkgReady", "共有" + pkgReady.size() + "个:" + StringUtils.join(pkgReady, ","));
        request.setAttribute("pkgOnging", "共有" + pkgOnging.size() + "个:" + StringUtils.join(pkgOnging, ","));
        request.setAttribute("pkgFinished", "共有" + pkgFinished.size() + "个:" + StringUtils.join(pkgFinished, ","));

        request.setAttribute("unstarted", unstarted);
        request.setAttribute("finished", finished);
        request.setAttribute("onging", onging);

        request.setAttribute("currentRun", RoundSupervisor.getCurrentRun().tohumanable());
        return "elpa/index";
    }

    @RequestMapping(value = "d8")
    public CommonResponse d8() {
        CommonResponse com = new CommonResponse();

        //pkgFetchService.d8();
        //pkgFetchService.downloadPackage("nclip");
        //pkgBuildService.buildPackage("nclip");
        com.setData(recipesService.randomRecipe());
        Map<String, ArchiveVo> map = LocalCache.getArchive();

        //pkgBuildService.writeArchiveJSON();
        //recipesService.writeRecipesJson();
        pkgBuildService.writeArchiveJSON();
        return com;
    }

    @RequestMapping(value = "updateRecipeJSON")
    public CommonResponse updateRecipeJSON() {
        CommonResponse com = new CommonResponse();
        com.setData(recipesService.getAllRecipeList());
        recipesService.writeRecipesJson();
        return com;
    }

    @RequestMapping(value = "updateArchiveJSON")
    public CommonResponse updateArchiveJSON() {
        CommonResponse com = new CommonResponse();
        com.setData(LocalCache.getArchiveJSON());
        pkgBuildService.writeArchiveJSON();
        return com;
    }

    @RequestMapping(value = "updateAC")
    public CommonResponse updateAC() {
        CommonResponse commonResponse = new CommonResponse();
        String htmlPath = PelpaUtils.getHtmlPath();
        File archiveContents = new File(htmlPath + "packages/archive-contents");
        String result = archiveContentsGenerator.generator();
        try {
            if (StringUtils.isNotBlank(result)) {
                FileUtils.writeStringToFile(archiveContents, result, "UTF-8");
            }
        } catch (Exception e) {
            //
        }
        commonResponse.setData(result);
        return commonResponse;
    }

    @RequestMapping(value = "build.html")
    public CommonResponse build(String pkgName) {
        CommonResponse commonResponse = new CommonResponse();
        if (StringUtils.isNotBlank(pkgName)) {
            RecipeDo recipeDo = RecipeParser.parsePkgRecipe(pkgName);
            SimpleResult simpleResult = pkgBuildService.buildPackage(pkgName);
            commonResponse.setData(simpleResult);
        }
        return commonResponse;
    }

}

@@ -258,16 +258,58 @@
 Result;%0A
+import org.popkit.core.logger.LeapLogger;%0A
 import o
@@ -4996,40 +4996,26 @@
     
-File archiveContents = new File(
+String fileName = 
 html
@@ -5048,16 +5048,66 @@
 ontents%22
+;%0A        File archiveContents = new File(fileName
 );%0A     
@@ -5177,16 +5177,77 @@
   try %7B%0A
+            LeapLogger.info(%22write content to %22 + fileName);%0A
         
@@ -5359,17 +5359,8 @@
 sult
-, %22UTF-8%22
 );%0A 
@@ -5416,18 +5416,101 @@
         
-//
+LeapLogger.warn(%22error write to archive-contents file failed! fileName=%22 + fileName);
 %0A       

print log info