$(function() {


    var chartTimestampArray = [],
        logTimestampArray = [],
        selectedTimestampArray = [];

	Highcharts.setOptions({
		global: {
			useUTC: false
		},
		lang: {
			noData: "Ждём данные.."
		}
	});



	renderQuantilesChart();

	function renderQuantilesChart()
	{
	    loadQuantilesChart();
	    /*loadFragments();

	    function loadFragments() {
	        $('#fragmentsContainer').load("/mobile/render_fragments_modal", {
                'test_id': $('#global-test-id').data('testid')
            })
        }*/

        // Рисуем график
        function loadQuantilesChart(start, end) {
        	$("#krutilka").show();
            function _drawChart(data) {
                var chartData = data.data;

                // Create the chart
                Highcharts.stockChart('mobileQuantilesChartContainer', {
                    chart: {
                        zoomType: 'x',
                        width: $('#mobileQuantilesChartContainer').width(),
                        style: {
                            fontFamily: 'Yandex Sans Text Web'
                        }
                    },
                    navigator: {
                        enabled: false
                    },
                    scrollbar: {
                        enabled: false
                    },

                    yAxis: {
                        opposite: false,
                        title: {
                            text: null
                        }
                    },
                    xAxis: {
                        type: 'datetime',
                        crosshair: {
                            snap: true
                        }
                    },

                    plotOptions: {
                        series: {
                            animation: false,
                            shadow: false,
                            states: {
                                hover: {
                                    enabled: false
                                }
                            },
                            marker: {
                                enabled: false,
                                states: {
                                    hover: {
                                        enabled: false
                                    }
                                }
                            },
                            turboThreshold: 0
                        }
                    },

                    title: {
                        text: ''
                    },
                    
                    rangeSelector: {

                        buttons: [{
                            type: 'all',
                            text: 'All'
                        }],
                        selected: 0,
                        inputDateFormat: '%H:%M:%S',
                        inputEditDateFormat: '%H:%M:%S'
                    },


                    series: chartData,

                    tooltip: {
                        valueDecimals: 3,
                        animation: false,
                        shared: true,
                        borderRadius: 4,
                        borderWidth: 1,
                        borderColor: '#999',
                        hideDelay: 10,
                        xDateFormat: '%H:%M:%S',
                        crosshairs: {
                            width: 1,
                            color: '#BBB',
                            zIndex: 100
                        },
                        style: {
                            fontSize: '15px',
                            fontFamily: '"Yandex Sans Text Web", Arial, Helvetica, sans-serif'
                        }
                    },
                    
                    legend: {
                    	enabled: true
                    }

                });
                $('#krutilka').hide();
                $('#chartKrutilka').hide();
            }

            $.ajax({
                url: "/mobile/plot.json",
                data: {
                    'type': 'quantiles',
                    'test_id': $('#global-test-id').data('testid'),
                    'start': start,
                    'end': end
                },
                method: 'POST',
                dataType: 'json',
                success: function (data) {
                    _drawChart(data);
                    var $fragments = $('.fragmentsTableRow');
                    if ($fragments.length) {
                        $('#fragmentsButton').show();
                        $fragments.on('click', function(event){
                            var chart = getCurrentChart();
                            console.log(chart);
                            chart.xAxis[0].setExtremes($(this).data('start'), $(this).data('end'));
                            event.stopPropagation();
                        })
                    }
                }
            });

            function getQuantilesChart() {
                for (var c = 0; c < Highcharts.charts.length; c++) {
                    var ch = Highcharts.charts[c];
                    if (ch !== undefined && ch.container.offsetParent !== undefined && ch.container.offsetParent.id === 'quantiles_tab_panel') {
                        return Highcharts.charts[c]
                    }
                }
            }

            // Ресайзим график
            $(window).resize(function () {
                var chart = getQuantilesChart();
                chart.setSize($('#mobileQuantilesChartContainer').width(), 400, false)
            });
        }
	}


    function renderRawChart()
    {
        loadRawChart();
        drawSyncs();
        
        // Рисуем график
        function loadRawChart(start, end) {
        	$("#krutilka").show();
            chartTimestampArray = [];
            // убираем повторы
			/*selectedTimestampArray = selectedTimestampArray.filter( function( item, index, inputArray ) {
			 return inputArray[index] == index;
			 });*/

            function _drawChart(data) {

                data = data.data;
                var chartData = data, chartDataLen = chartData.length;

                for (var i = 0; i < chartDataLen; i++) {
                    chartTimestampArray.push(chartData[i][0])
                }

                // Create the chart
                var chart = Highcharts.stockChart('mobileRawChartContainer', {
                    chart: {
                        backgroundColor: 'rgba(255,255,255,0.8)',
                        zoomType: 'x',
                        width: $('.container-fluid').width() / 2,
                        style: {
                            fontFamily: 'Yandex Sans Text Web'
                        },
                        events: {
                            click: function (event) {
                                var timestamp = getCurrentChart_point(event);
                                var logTimestamp = closest_timestamp(timestamp, logTimestampArray);
                                //$('.log_entry').removeClass('table-info');
                                var $log_entry = $('#log_entry_' + logTimestamp);
                                var chartTimestamp = closest_timestamp(logTimestamp, chartTimestampArray);
                                console.log(chartTimestamp);
                                if ($log_entry.hasClass('table-info')) {
                                    var chart = getCurrentChart();
                                    chart.xAxis[0].removePlotLine('pseudoCrosshair_' + chartTimestamp);
                                    removeTimestampFromSelected(logTimestamp);
                                    $log_entry.removeClass('table-info');
                                } else if ($log_entry[0] !== undefined) {
                                    selectedTimestampArray.push([logTimestamp, chartTimestamp]);
                                    chartDrawLine(chartTimestamp);
                                    $log_entry.addClass('table-info');
                                }

                                try {
                                    var scrollTo = document.getElementById('log_entry_' + logTimestamp).offsetTop;
                                    var scrollBox = document.getElementById('logScrollBox');
                                    scrollBox.scrollTop = scrollTo;
                                } catch (e) {
                                    if (e instanceof TypeError) {
                                        console.log('No logs for this period.')
                                    } else {
                                        throw e
                                    }
                                }
                                //log_entry.scrollTop(scrollTo);
                            }
                        }
                    },

                    rangeSelector: {

                        buttons: [{
                            type: 'all',
                            text: 'All'
                        }],
                        selected: 0,
                        inputDateFormat: '%H:%M:%S.%L',
                        inputEditDateFormat: '%H:%M:%S.%L'
                    },

                    yAxis: {
                        opposite: false,
                        title: {
                            text: null
                        }
                    },
                    xAxis: {
                        type: 'datetime',
                        crosshair: {
                            snap: false
                        }
                    },

                    plotOptions: {
                        series: {
                            animation: false,
                            shadow: false,
                            states: {
                                hover: {
                                    enabled: false
                                }
                            },
                            marker: {
                                enabled: false,
                                states: {
                                    hover: {
                                        enabled: false
                                    }
                                }
                            },
                            turboThreshold: 0
                        }
                    },

                    title: {
                        text: ''
                    },

                    series: [{
                        name: 'Current, mA',
                        data: chartData,
                        pointStart: chartData[0][0],
                        pointInterval: 1000
                    }],

                    tooltip: {
                        valueDecimals: 3,
                        animation: false,
                        borderRadius: 4,
                        borderWidth: 1,
                        borderColor: '#999',
                        hideDelay: 10,
                        xDateFormat: '%H:%M:%S.%L',
                        crosshairs: {
                            width: 1,
                            color: '#BBB',
                            zIndex: 100
                        },
                        style: {
                            fontSize: '15px',
                            fontFamily: '"Yandex Sans Text Web", Arial, Helvetica, sans-serif'
                        }
                    }

                });
                $('#krutilka').hide();
                $('#chartKrutilka').hide();

                loadTable(chart.xAxis[0].min, chart.xAxis[0].max, $('#grep').val())
            }

            $.ajax({
                url: "/mobile/plot.json",
                data: {
                    'type': 'raw',
                    'test_id': $('#global-test-id').data('testid'),
                    'start': start,
                    'end': end
                },
                method: 'POST',
                dataType: 'json',
                success: function (data) {
                    _drawChart(data);
                    _drawSyncs();
                }
            });

            function _drawSyncs() {

                $.ajax({
                    url: "/mobile/syncs.json",
                    data: {
                        'test_id': $('#global-test-id').data('testid'),
                    },
                    method: 'POST',
                    dataType: 'json',
                    success: function (data) {
                        $.each(data, chartDrawSyncLine)
                    }
                });


            }

        }

        // Заполняем таблицу
        function loadTable(start, end, grep) {

            var logTable = $('#log_table');
            logTable.html(''); // clear
            logTable.load("/mobile/logs.json", {
                'start': start, 'end': end, 'grep': grep, 'test_id': $('#global-test-id').data('testid')
            }, function() {
                $('.log_entry').each(function(){
                    logTimestampArray.push($(this).data('timestamp'));
                    $(this).on('click',
                        function () {
                            //$('.log_entry').removeClass('table-info');
                            var chartTimestamp = closest_timestamp(parseInt($(this).data('timestamp')), chartTimestampArray),
                                logTimestamp = $(this).data('timestamp');

                            if ($(this).hasClass('table-info')) {
                                var ch = getCurrentChart();
                                ch.xAxis[0].removePlotLine('pseudoCrosshair_' + chartTimestamp);
                                removeTimestampFromSelected(logTimestamp);
                                $(this).removeClass('table-info');
                            }
                            else {
                                chartDrawLine(chartTimestamp);
                                selectedTimestampArray.push([logTimestamp, chartTimestamp]);
                                $(this).addClass('table-info');
                            }
                        });
                });
                $('#grepContainer').show();

                // Расставляем выбранные ранее отметки
                $.each(selectedTimestampArray, function (i, ts) {
                    var logEntry = $('#log_entry_' + ts[0]);
                    if (logEntry[0]) {
                        logEntry.addClass('table-info');
                        chartDrawLine(closest_timestamp(ts[0], chartTimestampArray));
                    }
                });
            });
        }

        // Грепалка

        $('#submitGrep').on('click', function () {
            logTimestampArray = [];
            var chart = getCurrentChart();
            loadTable(chart.xAxis[0].min, chart.xAxis[0].max, $('#grep').val());
            try {
                var chartDataLen = chartTimestampArray.length;
                for (var i = 0; i < chartDataLen; i++) {
                    var ts = chartTimestampArray[i];
                    chart.xAxis[0].removePlotLine('pseudoCrosshair_' + ts)
                }
            } catch (e) {
                console.log(e)
            }
        });

        //stolen from here http://stackoverflow.com/questions/8584902/get-closest-number-out-of-array
        function closest_timestamp(num, arr) {
            var curr = arr[0];
            var diff = Math.abs(num - curr);
            var arrlen = arr.length;
            for (var val = 0; val < arrlen; val++) {
                var newdiff = Math.abs(num - arr[val]);
                if (newdiff < diff) {
                    diff = newdiff;
                    curr = arr[val];
                }
            }
            return curr;
        }

        // Рисует линию на графике (юзается и при клике по графику, и при клике на лог)
        function chartDrawLine(timestamp) {
            var chart = getCurrentChart();
            chart.xAxis[0].addPlotLine({
                value: timestamp,
                color: '#f2e088',
                width: 2,
                id: 'pseudoCrosshair_' + timestamp
            })
        }

        // Рисует линию на графике (юзается и при клике по графику, и при клике на лог)
        function chartDrawSyncLine(timestamp) {
            var chart = getCurrentChart();
            chart.xAxis[0].addPlotLine({
                value: timestamp,
                color: 'red',
                width: 2,
                id: 'pseudoCrosshair_' + timestamp
            })
        }


        // Таймстемпы на графике могут все время меняться из-за зума, поэтому храним неуникальное соответствие таймстемпа в логах и на графике.
        function removeTimestampFromSelected(timestamp) {
            var ts = $.grep(selectedTimestampArray, function (e) {
                return e[0] === timestamp;
            });
            var index = selectedTimestampArray.indexOf(ts[0]);
            if (index > -1) {
                selectedTimestampArray.splice(index, 1);
            }
        }


        // Берет ближайший к клику таймстемп на графике
        function getCurrentChart_point(event) {
            var chart = getCurrentChart();
            var ev = chart.pointer.normalize(event);
            var point = chart.series[0].searchPoint(ev, true);
            if (point) {
                return point.category;
            }
        }

        function getCurrentChart() {
            for (var c = 0; c < Highcharts.charts.length; c++) {
                var ch = Highcharts.charts[c];
                console.log( ch.container.offsetParent);
                if (ch !== undefined && ch.container.offsetParent !== null && ch.container.offsetParent.id === 'mobileRawChartColumn') {
                    return Highcharts.charts[c]
                }
            }
        }

        // Ресайзим график
        $(window).resize(function () {
            var chart = getCurrentChart();
            chart.setSize($('#mobileRawChartContainer').width(), 600, false)
        });
    }

    function renderFragmentsTable() {
        var $fragmentsTableContainer = $('#mobileFragmentsTableContainer');
        $fragmentsTableContainer.html(''); // clear
        $fragmentsTableContainer.load("/mobile/render_fragments_table", {
            'test_id': $('#global-test-id').data('testid')
        }, function () {
            var $fragments_table = $('#fragments_table');
            $fragments_table.off();
            $fragments_table.on( "click", "th", function() {
                $.bootstrapSortable(true);
            });
        })
    }

    $('#quantiles_tab_tab').on('shown.bs.tab', function(event) {
		if ($('#mobileQuantilesChartContainer').html() === "") {
		    console.log('quantiles_tab_activated');
	        renderQuantilesChart();
        }
		event.preventDefault();
	});

	$('#fragments_tab_tab').on('shown.bs.tab', function(event) {
		if ($('#mobileFragmentsTableContainer').html() === "") {
		    console.log('fragments_tab_activated');
	        renderFragmentsTable();
        }
		event.preventDefault();
	});

	$('#raw_tab_tab').on('shown.bs.tab', function(event) {
		if ($('#mobileRawChartContainer').html() === "") {
		    console.log('raw_tab_activated');
	        renderRawChart();
        }
		event.preventDefault();
	});

    $( document ).ready(function() {
        console.log(location.hash);
        var $active_nav_link = $('.nav-link.active');
        if (location.hash === '#quantiles' || $active_nav_link.data("tab") === "quantiles") {
            console.log('quantiles_tab');
            $('#quantiles_tab_tab').tab('show');
        } else if (location.hash === '#raw' || $active_nav_link.data("tab") === "raw") {
            console.log('raw_tab');
            $('#raw_tab_tab').tab('show');
        }
    });

});