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

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.yaml.snakeyaml.Yaml;

/**
 *
 * @author LH
 */
public class PlProcessor implements HttpHandler 
{
    private ArrayList<String[]> pool1=new ArrayList<>(),pool2=new ArrayList<>();//wird verschoben so dass jedes Element drankommt und dann erst von vorne begonnen wird
    private int poolSize=0;
    private int unusedElems=0;
    private String path;
   /* public PlProcessor(String PlPath)
    {
    }*/
      //<editor-fold defaultstate="collapsed" desc=" Serialisierunbgsscheissss ">
    public ArrayList<String[]> getPool1()
    {
        return pool1;
    }

    public void setPool1(ArrayList<String[]> pool1)
    {
        this.pool1 = pool1;
    }

    public ArrayList<String[]> getPool2()
    {
        return pool2;
    }

    public void setPool2(ArrayList<String[]> pool2)
    {
        this.pool2 = pool2;
    }

    public int getPoolSize()
    {
        return poolSize;
    }

    public void setPoolSize(int poolSize)
    {
        this.poolSize = poolSize;
    }

    public int getUnusedElems()
    {
        return unusedElems;
    }

    public void setUnusedElems(int unusedElems)
    {
        this.unusedElems = unusedElems;
    }

    public String getPath()
    {
        return path;
    }

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

    public static Yaml getYp()
    {
        return yp;
    }

    public static void setYp(Yaml yp)
    {
        PlProcessor.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)
    {
        pool1=new ArrayList<>();
        if(!reload)
        {
        pool2=new ArrayList<>();//wichtig bei reload
        }   
        List<String[]> list = PLReader.readList(path);
        if(list==null)
        {
            return;
        }
        String[] g0 = list.get(0);//0-liste muss anderst verarztet werden
        for (String etr : g0)
        {
            pool1.add(new String[]{etr});//randomizer arbeitetblockweise und einzeleinträge=neue Blöcke
        }
        list.remove(0);//NA DU SCHEISSER; WIE ISTS NACH SO LANGER ZEIT GEKILLT ZU WERDEN!
        for (String[] blox : list)
        {
            pool1.add(blox);
        }
        if(reload)
        {
            for (String[] el : pool2)
            {
                 int idx = pool1.indexOf(el);
                 if(idx==-1)
                 {
                     pool2.remove(el);//entfernte elemente killen
                 }
                 else
                 {
                     pool1.remove(idx);//subtrahieren der bereits gespielten elemente
                 }
            }
        }
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        System.out.println("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        System.out.println("ArrayResult of the Internal List");
        System.out.println("\n"+yp.dump(pool1));
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        System.out.println("List2; nur bei Reload wixtix");
        System.out.println("\n"+yp.dump(pool2));
        System.out.println("ENd of Block:MasterbLOCK");
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        System.out.println("<><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>");
        System.out.println("><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><><");
        if(!reload)
            poolSize = pool1.size();
        else
            poolSize=pool1.size()+pool2.size();
        unusedElems = poolSize;
    }
    
    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 String getBlock()
    {
        String response = "";
        double rm = Math.random();//Zufallsselektor
        int selection = (int) (rm*unusedElems);//macht nix...
        String[] loadedBlock = pool1.get(selection);
        if(loadedBlock[0].length()>5)
        {
        pool2.add(loadedBlock); //legts in benutzt-Pool ab //wenn Pool1 leer dann tauschen diese ihren Platz
        }
        else
        {
            poolSize--;
            unusedElems--;
            pool1.remove(selection);//nimmts vorm nxten durchlauf raus
            return getBlock();
        }
        pool1.remove(selection);//nimmts vorm nxten durchlauf raus
        unusedElems--;
        if(unusedElems==0)//Bei ende refill
        {
            pool1=pool2;
            pool2=new ArrayList<>();
            unusedElems=poolSize;
        }
        for (String line : loadedBlock)
        {
            response+="\n"+line;
            
        }
        response=response.replaceAll("\\\n\\\n", "\\\n");
        return response;
    }
}

