let u = new URL(location.href)
urlPrivateAPI = u.origin + '/api'

api = new API({
    url: urlPrivateAPI,
    timeout: 10000, // 10 sec
})


document.addEventListener('DOMContentLoaded',  ()=> {
    google.charts.load('current', {'packages':['corechart']});

    let model = new ListModel({
        template: {
            id: 'champ',
        },
        container: 'champs',
        preFunc: (r) => {
            r.champ = `${r.zoneName}. ${r.champName}`
            r.accuracy = (r.won * 100) / (r.won + r.lost)

            r.avgPrice = Math.round(r.avgPrice*100)/100
            r.accuracy = Math.round(r.accuracy*100)/100
        },
    })

    let s = new Select({
        field: document.getElementById('strategyID'),
        key: 'strategyID',
        name: 'name'
    })

    s.on('select', strategyID => {
        if (strategyID) {
            api.req({
                func: 'listStrategyRatedChampStats',
                data: strategyID,
                onSuccess: resp => {
                    model.setList(resp)
                }
            })
        } else {
            model.clear()
        }
    })

    s.on('select', strategyID => {
        if (strategyID) {
            api.req({
                func: 'getStrategyRatedHistory',
                data: strategyID,
                onSuccess: resp => {
                    var rows = []
                    if (Array.isArray(resp)) {
                        resp.forEach(item => {
                            rows.push([
                                new Date(item.date * 1000),
                                item.profit
                            ])
                        })
                    }

                    drawChart(strategyID, rows)
                }
            })
        } else {
            drawChart(0, [])
        }
    })

    api.req({
        func: 'listStrategies',
        onSuccess: resp => {
            s.setList(resp)
        }
    })
})



        //google.charts.setOnLoadCallback(drawChart);
  
function drawChart(strategyID, rows) {
    var data = new google.visualization.DataTable();
    data.addColumn('date', 'Date');
    data.addColumn('number', 'Алгоритм ' + strategyID);
    //data.addColumn('number', 'Алгоритм 2');
    //data.addColumn('number', 'Алгоритм 3');

    console.log(rows)

    data.addRows(rows)

    var options = {
        chart: {
          title: 'Кривая доходности',
        },
        width: 900,
        height: 500
    };
    var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));

    //chart.draw(data, google.charts.Line.convertOptions(options));
    chart.draw(data, options);
}