/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.edu.pwr.nlpmonitor;

import java.io.File;
import java.io.FilenameFilter;

import java.util.Date;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 *
 * @author www_zsk
 */

class WorkerStatus {
    String tool_path="/mnt/requests";
    int offset=3*61000+11000;
    
    static HashMap <String,HashMap<String,Long>> dircache =new HashMap<>();
    
    private long getLastCached(String type,String tool)
    {  Date start=new Date();
        String dirname=tool_path+'/'+tool+'/'+type;
       File myDir = new File(dirname);
       long larger=0; 
       HashMap<String,Long> cache=null;
       synchronized (dircache)
        { 
          cache=dircache.get(dirname);
          if (cache==null)
          {   cache=new HashMap<>();
              dircache.put(dirname, cache);
          }
          
        }
        
          File[] tab = myDir.listFiles();
               
       if (tab!=null)
       {  
           
           for (File file : tab) {
               long lastModified=0;
               Long res;
               synchronized (cache)
               {
                  res=cache.get(file.getAbsolutePath());
               }
               if (res==null)
               {  start=new Date();
                  lastModified=file.lastModified();
                   //System.out.println("Last modified "+file.getAbsolutePath()+"= "+((new Date()).getTime()-start.getTime()));
                 res=larger;
                 synchronized (cache)
                 {
                 cache.put(file.getAbsolutePath(), res);
                 }
               }
               else
                   lastModified=res;
               if (lastModified>larger) larger=lastModified;
           
           }   
       }
       //System.out.println(tool+" "+((new Date()).getTime()-start.getTime()));
       if (larger==0) return -1;
       long diff=new Date().getTime()-larger+offset;
                
       return diff;
    }
    
    
    JSONArray get() {
        Date start=new Date();
        JSONArray result=new JSONArray();
        File file = new File(tool_path);
        
        String[] directories = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File current, String name) {
                return new File(current, name).isDirectory();
            }
        });
        
        //System.out.println("Dir 1st list "+((new Date()).getTime()-start.getTime()));
        if (directories==null)
        {  
           
        }
        else
        for (String tool:directories)
          //if (tool.contains("liner2"))
        {  
            
            JSONObject status=getworkerStatus(tool);
        
           result.put(status);
        }    
       //System.out.println("Czas calosci"+((new Date()).getTime()-start.getTime()));
        return result;
    }

    private JSONObject getworkerStatus(String tool) {
        JSONObject status=new JSONObject();
        Date start=new Date();
        status.put("last_done",formatTimeDiff(getLastCached("done",tool)));
        
        int qn=getNumber("queue",tool);status.put("queue",qn);
        long qf=-1;if (qn!=0) qf=getFirst("queue",tool); status.put("first_queue",formatTimeDiff(qf));
        
        int pn=getNumber("progress",tool);status.put("progress",pn);
        long pf=-1;if (pn!=0) pf=getFirst("progress",tool); status.put("first_progress",formatTimeDiff(pf));
        
        status.put("name", tool);
       // System.out.println("Czas "+tool+" "+((new Date()).getTime()-start.getTime()));
        return status;
        
    }

    private long getLast(String type,String tool) {
       File myDir = new File(tool_path+'/'+tool+'/'+type);
       Date start=new Date();
       long larger=0;
       
       File[] tab = myDir.listFiles();
       if (tab!=null)
       {   
           
           for (File file : tab) {
           if (file.lastModified()>larger)
           {    larger=file.lastModified();
           }
           }   
       }
       //System.out.println(tool+" "+((new Date()).getTime()-start.getTime()));
       if (larger==0) return -1;
       long diff=new Date().getTime()-larger;
                
       return diff;
    }
    
    
    private long getFirst(String type,String tool) {
       File myDir = new File(tool_path+'/'+tool+'/'+type);
       
       long larger=new Date().getTime()+2*offset;
       Date start=new Date();
       
        File[] tab = myDir.listFiles();
       if (tab!=null)
       for (File file : tab) 
       {Long last=file.lastModified();
             if (last<larger) {
                 larger=last;
             //break;
          } 
       }
       //System.out.println("GetFIRTS "+tool+" "+((new Date()).getTime()-start.getTime()));
       if (tab==null) return -1;
       if (larger==0) return -1;
       if (tab.length==0) return -1;
       long diff=new Date().getTime()-larger+offset;
       
       return diff;
    }
    
    private String formatTimeDiff(long diff)
    { if (diff ==-1) return "-";
      
       long diffdays = (long) (diff / (60 * 60 * 1000*24));
      long diffhours = (long) ((diff -diffdays*60*60*1000*24)/ (60 * 60 * 1000));
       long diffminutes = (long) ((diff-diffdays*60*60*1000*24-diffhours*60*60*1000) / (60 * 1000));
       long diffseconds = (long) ((diff-diffminutes*60*1000) / (1000));
       String res="";
       
       if (diffdays>0)
            res+=diffdays+"d";
       if (diffdays>0 || diffhours>0)
            res+=diffhours+"h";
       if (diffdays>0 || diffhours>0 || diffminutes!=0)
            res+=diffminutes+"m";
       
       if (diffhours==0 && diffdays==0)
            res+=diffseconds+"s";
           
       return res;
    }

    private int getNumber(String type, String tool) {
       File myDir = new File(tool_path+'/'+tool+'/'+type);
       
       int val=0;
       File[] tab = myDir.listFiles();
       if (tab!=null)
       {
           val=tab.length;
       }
        return val; 
    }

}
