/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package de.nplusc.izc.iZpl;

import de.nplusc.izc.iZpl.Utils.PLReader;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import static de.nplusc.izc.iZpl.PlProcessor.failRSP;
import de.nplusc.izc.tools.IOtools.FileTK;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.prefs.Preferences;
import org.yaml.snakeyaml.Yaml;

/**
 *
 * @author LH
 */
public class PlProcessorV2 implements HttpHandler 
{
    private HashMap<String,PlayListItem> pool;
    private String path;
    private List<String> availEtrs;

    /* public PlProcessor(String PlPath)
    {
    }*/
    //<editor-fold defaultstate="collapsed" desc=" Serialisierunbgsscheissss ">
    public HashMap<String, PlayListItem> getPool()
    {
        return pool;
    }

    public void setPool(HashMap<String, PlayListItem> pool)
    {
        this.pool = pool;
    }

    public String getPath()
    {
        return path;
    }

    public void setPath(String path)
    {
        this.path = path;
    }

    public List<String> getAvailEtrs()
    {
        return availEtrs;
    }

    public void setAvailEtrs(List<String> availEtrs)
    {
        this.availEtrs = availEtrs;
    }
    

    public static Yaml getYp()
    {
        return yp;
    }

    public static void setYp(Yaml yp)
    {
        PlProcessorV2.yp = yp;
    }

    public static String getFailRSP()
    {
        return failRSP;
    }

    public static void setFailRSP(String failRSP)
    {
        PlProcessor.failRSP = failRSP;
    }
    //</editor-fold>
    
    
    public void InitializeOnPath(String PlPath)
    {
        path=PlPath;
        reloadLists();
    }
    
    private static Yaml yp = new Yaml();
    public void reloadLists()
    {
        reloadLists(false);
    }
    
    public void reloadLists(boolean reload)
    {
        availEtrs = new ArrayList<>();//cache flush and reinit...
        if(!reload)
        {
            pool=PLReader.readListAlternative(path, 40, 1);
        }
        else
        {
            HashMap<String,PlayListItem> poolTemp = PLReader.readListAlternative(path, 40, 1);
            Set<String> keys = pool.keySet();
            for (String key : keys)
            {
                if(poolTemp.containsKey(key))
                {
                    PlayListItem pli = poolTemp.get(key);
                    PlayListItem spli = pool.get(key);
                    pli.setCountPlayed(spli.getCountPlayed());
                }
            }
            pool = poolTemp;
        }
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        System.out.println("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        System.out.println("ArrayResult of the Internal List");
        System.out.println("\n"+yp.dump(pool));
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        System.out.println("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        
        //pregenerieren von Cache...
        Set<String> keys = pool.keySet();
        for (String key : keys)
        {
            PlayListItem pli = pool.get(key);
            if(pli.getCountPlayed()>=pli.getTargetPlaycount())
            {
                pli.setCountPlayed(pli.getCountPlayed());
            }
            else
            {
                availEtrs.add(key);
            }
        }
    }
    
    public static String failRSP = "http://localhost:9263/lst.m3u";
    
    
    @Override
    public void handle(HttpExchange t) throws IOException 
    {
        String time = new Date(System.currentTimeMillis()).toString();
        System.out.println("IZPL-HAndler:Received Request at:"+time);
        System.err.println("IZPL-HAndler:Received Request at:"+time);
         String response = "Nixda mit glotzen...\n Hier gibts keine Filezzzzzzz, also raus und zwar dalli";
       /* if(!t.getRemoteAddress().getHostName().equalsIgnoreCase("localhost"))
        {
        t.sendResponseHeaders(403, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
        return;
        }*/
        response = "#EXTM3U";
                //  \N am anfang jeder zeile....
        String tr = getBlock();
        response+=tr;
        response+="\nhttp://localhost:9263/lst.m3u";//:9263/lst.m3u";//continueCode //Exit wird durch unblock woanderst realisiert
        System.out.println("IZPL-HAndler:Responded with:"+response);
        t.sendResponseHeaders(200, response.length());
        Headers responseHeaders = t.getResponseHeaders();
        responseHeaders.set("Content-Type", "audio/x-mpegurl");

        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        failRSP=response;
        os.close();
        time = new Date(System.currentTimeMillis()).toString();
        System.out.println("IZPL-HAndler:Answered Request at:"+time);
    }
    
    public boolean resetted;
    public String getBlock()
    {
        String response = "";
        double rm = Math.random();//Zufallsselektor
        int selection = (int) (rm*availEtrs.size());//macht nix...
        PlayListItem pli = pool.get(availEtrs.get(selection));
        if(pli.getCountPlayed()>=pli.getTargetPlaycount()-1)
        {
            availEtrs.remove(selection);//vom Cache streichen damit RNG es nicht mehr wählen kann
        }
        response = pli.getM3UElement();
        pli.setCountPlayed(pli.getCountPlayed()+1);
        resetted=false;
        if(availEtrs.size()<1)
        {
            for (String key : pool.keySet())
            {
                pli=pool.get(key);
                pli.setCountPlayed(0);
                availEtrs.add(key);
            }
            resetted=true;
        }
        response=response.replaceAll("\\\n\\\n", "\\\n");
        return response;
    }
}

