/// <reference path="../GeneratedArtifacts/viewModel.js" />
/// <reference path="../Scripts/c1ls-4.0.20142.37.js" />

if (typeof c1ls === "undefined") {
    window.location.href = "http://bit.ly/c1ls-nuget";
}

// Customize the settings in the following function,
// if desired, but do not remove any of these lines

myapp.OlapInitialView.created = function (screen) {

    // Replace with the relative URL for your Web API, if different
    screen.baseUrl = "../API/Olap/";

    // Set initial field names for preloading an OLAP view (no duplicates)
    screen.RowField = "Salesperson";
    screen.ColumnField = "ShipperName";
    screen.ValueField = "Freight";

    // Set display of grand totals (none, rows, columns, all)
    screen.ShowTotals = "all";

    // Verify that the server package is installed
    $.getJSON(screen.baseUrl).error(function (args) {
        window.location.href = "http://bit.ly/c1ls-server";
    });

    // Get data from the server if the screen collection changes
    screen.Invoices.oncollectionchange = function () {
        if (screen.RowField !== "" && screen.ValueField !== "") {
            myapp.OlapInitialView.Update_execute(screen);
        }
    };

    // Force load the screen collection
    if (!screen.Invoices.isLoaded) {
        screen.Invoices.load();
    }
};

myapp.OlapInitialView.Invoices_render = function (element, contentItem) {

    var div = $("<div style='padding: 4px 12px 12px 12px;'/>");
    div.appendTo($(element));

    var rowsLabel = $("<p>Row Fields:</p>");
    rowsLabel.appendTo(div);

    var rows = $("<select id='olapRows' data-role='listview' class='msls-listview'/>");
    rows.appendTo(div);

    var colsLabel = $("<p>Column Fields:</p>");
    colsLabel.appendTo(div);

    var cols = $("<select id='olapColumns' data-role='listview' class='msls-listview'/>");
    cols.appendTo(div);

    var valsLabel = $("<p>Value Fields:</p>");
    valsLabel.appendTo(div);

    var vals = $("<select id='olapValues' data-role='listview' class='msls-listview'/>");
    vals.appendTo(div);

    var totalsLabel = $("<p>Show Totals:</p>");
    totalsLabel.appendTo(div);

    var totals = $("<select id='olapTotals' class='msls-listview'/>");
    totals.appendTo(div);

    var options = [];
    options.push("<option selected value='none'>None</option>");
    options.push("<option value='rows'>Rows</option>");
    options.push("<option value='columns'>Columns</option>");
    options.push("<option value='all'>All</option>");

    totals.html(options.join("\r\n"));
    totals.val(contentItem.screen.ShowTotals);

    function checkUpdate() {
        var update = contentItem.screen.findContentItem("Update");
        update.isEnabled = (vals.val() !== "") && (rows.val() !== "");
    }

    function preventDuplicates(ctrl, value) {
        if (ctrl.val() === value) {
            ctrl.prop("selectedIndex", 0);
            ctrl.selectmenu("refresh");
        }
    }

    rows.bind("change", function () {
        var v = rows.val();
        contentItem.screen.RowField = v;
        preventDuplicates(cols, v);
        preventDuplicates(vals, v);
        checkUpdate();
    });

    cols.bind("change", function () {
        var v = cols.val();
        contentItem.screen.ColumnField = v;
        preventDuplicates(rows, v);
        preventDuplicates(vals, v);
        checkUpdate();
    });

    vals.bind("change", function () {
        var v = vals.val();
        contentItem.screen.ValueField = v;
        preventDuplicates(rows, v);
        preventDuplicates(cols, v);
        checkUpdate();
    });

    totals.bind("change", function () {
        contentItem.screen.ShowTotals = totals.val();
    });

    if (contentItem.children.length > 0) {
        var items = [];
        var first = contentItem.children[0];
        items.push("<option value=''>(Not Set)</option>");

        first.children.forEach(function (c) {
            if (c.isVisible && !c.valueModel[":@Hidden"]) {
                items.push("<option value='" + c.valueModel.name + "'>" + c.displayName + "</option>");
            }
        });

        rows.html(items.join("\r\n"));
        cols.html(items.join("\r\n"));
        vals.html(items.join("\r\n"));

        rows.val(contentItem.screen.RowField);
        cols.val(contentItem.screen.ColumnField);
        vals.val(contentItem.screen.ValueField);
    }

    checkUpdate();
};

myapp.OlapInitialView.OlapGrid_render = function (element, contentItem) {

    var screen = contentItem.screen;
    screen.olap = undefined;
    screen.doUpdate = myapp.OlapInitialView.updateGrid;
    screen.currentTab = "GridTab";

    var table = $("<table id='olapGrid'/>");
    table.appendTo($(element));

    $(".msls-tabs-container li").click(function (e) {
        var tab = $(this).data().mslsTabName;
        if (tab === "ChartTab") {
            screen.doUpdate = myapp.OlapInitialView.updateChart;
        }
        else if (tab === "GridTab") {
            screen.doUpdate = myapp.OlapInitialView.updateGrid;
        }
        if (tab !== screen.currentTab) {
            screen.currentTab = tab;
            screen.doUpdate(screen.olap);
        }
    });
};

myapp.OlapInitialView.OlapChart_render = function (element, contentItem) {

    if (typeof contentItem.screen.olap === "undefined") {
        return;
    }

    var screen = contentItem.screen;
    screen.doUpdate = myapp.OlapInitialView.updateChart;
    screen.currentTab = "ChartTab";

    var div = $("<div id='olapChart'/>");
    div.appendTo($(element));

    setTimeout(function () {
        var color = "#999999";

        div.wijbarchart({
            textStyle: {
                "font-family": c1ls.fontFamily
            },
            header: {
                visible: false,
                text: "Chart Header",
                textStyle: { fill: color }
            },
            legend: {
                visible: true,
                style: { stroke: color },
                textStyle: { fill: color, "font-size": 10, "font-weight": "bold" }
            },
            axis: {
                x: { labels: { style: { fill: color }}},
                y: { autoMin: false, min: 0, labels: { style: { fill: color }, textAlign: "near" }}
            },
            horizontal: true,
            stacked: true,
            showChartLabels: false,
            seriesList: screen.olap.Series,
            hint: screen.olap.Hint
        });
    }, 500);
};

myapp.OlapInitialView.Update_execute = function (screen) {

    var url = screen.baseUrl + "?row=" + screen.RowField + "&column=" + screen.ColumnField +
        "&value=" + screen.ValueField + "&totals=" + screen.ShowTotals;

    // TODO: Append parameter values to url, if any

    screen.closePopup();

    msls.showProgress(msls.promiseOperation(function (operation) {
        $.getJSON(url, function (data) {
            operation.complete(data);
        }).error(function (args) {
            operation.error(args);
        });
    }).then(function success(result) {
        screen.findContentItem("ChartTab").isVisible = true;
        screen.olap = c1ls.getJsonData(result, { totals: screen.ShowTotals });
        screen.doUpdate(screen.olap);
    }, function failure(args) {
        if (args.responseText.charAt(0) === "{") {
            var ex = $.parseJSON(args.responseText);
            msls.showMessageBox(ex.ExceptionMessage, { title: ex.Message });
        }
        else {
            msls.showMessageBox(args.statusText, { title: "HTTP Error " + args.status });
        }
    }));
};

myapp.OlapInitialView.updateGrid = function (olap) {

    if (typeof olap === "undefined")
        return;

    setTimeout(function () {
        $("#olapGrid").wijgrid({
            columnsAutogenerationMode: "none",
            columns: olap.Columns,
            data: olap.Rows,
            readAttributesFromData: true,
            showSelectionOnRender: false
        });

        $("#olapGrid").wijgrid("doRefresh");
    }, 500);
}

myapp.OlapInitialView.updateChart = function (olap) {

    if (typeof olap === "undefined")
        return;

    setTimeout(function () {
        $("#olapChart").wijbarchart({
            seriesList: olap.Series
        });

        $("#olapChart").wijbarchart("redraw");
    }, 500);
}