var V0;
var R0;
var a0;
var VSO;
var RSO;
var aSO;
var Z;
var Rc;
var nStep;
var dr;

class State{
    constructor(energy, jpi){
        this.energy = energy;
        this.jpi = jpi;
    }
}

var states = [];

function WSCal(){

    V0 = parseFloat(document.getElementById('V0').value);
    R0 = parseFloat(document.getElementById('R0').value);
    a0 = parseFloat(document.getElementById('a0').value);
    VSO = parseFloat(document.getElementById('VSO').value);
    RSO = parseFloat(document.getElementById('RSO').value);
    aSO = parseFloat(document.getElementById('aSO').value);
    Z = parseInt(document.getElementById('Z').value);
    Rc = parseFloat(document.getElementById('Rc').value);
    nStep = parseInt(document.getElementById('nStep').value);
    dr = parseFloat(document.getElementById('dr').value);

    let str = 'WoodsSaxon.py?V0=' + V0 + 
                           '&R0=' + R0 + 
                           '&a0=' + a0 +
                           '&VSO=' + VSO +
                           '&RSO=' + RSO +
                           '&aSO=' + aSO +
                           '&Z=' + Z +
                           '&Rc=' + Rc +
                           '&nStep=' + nStep +
                           '&dr=' + dr ;

    console.log(str);
    states = [];
    let client = new XMLHttpRequest();
    client.onreadystatechange = function() {
      let haha = client.responseText.split('\n').slice(11);
      
      haha.forEach(line =>{
          console.log(line);
          if( !line.includes("=====") && line.length != 0) {
              let jpi = line.substring(4, 12);
              let energy = parseFloat(line.substring(13,25));
              states.push(new State(energy, jpi));
          }
      });
    }
    client.open('GET', str, false);
    client.send();

    states.forEach(st =>{
        console.log( st.jpi + ", " + st.energy);
    })

    Plotly.purge("Plot_WS");

    let nEx = states.length;  
    let data = [];
    
    for( let i = 0; i < nEx; i++){  
      let newData = {
        x : [0,1], 
        y : [states[i].energy, states[i].energy], 
        mode:"lines", 
        name: states[i].jpi,
        type:"scatter"
      }
      data.push(newData);
    }

    let layout = {
        xaxis: {range: [-1, 2], title: { text : "Ex", standoff : 1}, mirror : "allticks", linewidth : "1"},
        yaxis: {range: [V0, 0], title: "Energy [MeV]" , mirror : "allticks", linewidth : "1"},  
        //dragmode : "pan",
        margin: { l: 40, r: 40, b : 60, t : 40},
        legend: {yanchor:"top", xanchor:"left", x:"0.01",y:"0.99"  }
      };

    Plotly.newPlot( "Plot_WS", data, layout, {responsive: true});
}