
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Print functions
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function OnPrintSelectedContent() {
    AjaxPrintExportContent();
}



function GetSelectedContentHtml() {

    var ContentDiv = GetSelectedContentInformationDiv();
    if (!ContentDiv)
        return "";

    var sHtml = ContentDiv[0].innerHTML;
    return sHtml;
}


function AjaxPrintExportContent() {

    var ContentType = GetSelectedContentType();
    var ContentTitle = GetSelectedContentTitle();
    var ValueString = GetSelectedContentPaneValueString()
    var LayoutString = LoadSelectedPaneLayoutStringFromCookie();;
    var FilterJsonString = LoadSelectedPaneFilterJsonStringFromCookie();
    var SettingsJsonString = LoadSelectedPaneSettingsJsonStringFromCookie();
    var ExportType = "Browser";
    var ExportFileExt = "html";

    var params = {
        "ContentType": ContentType,
        "ContentTitle": ContentTitle,
        "ValueString": ValueString,
        "LayoutString": LayoutString,
        "FilterJsonString": FilterJsonString,
        "SettingsJsonString": SettingsJsonString,
        "ExportType": ExportType,
        "ExportFileExt": ExportFileExt
    };

    // Modeless dialog for lengthly operations
    OpenPleaseWaitDialog("Print");

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxExportContent",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {

            ClosePleaseWaitDialog();

            if (response.Success) {
                // Convert base64 string to binary data;
                if (response.ExportDataBase64String && response.ExportDataBase64String.length > 0) {
                    var sHtmlResults = atob(response.ExportDataBase64String);
                    if (sHtmlResults && sHtmlResults.length) {

                        //ToastError("AjaxPrintExportContent", sHtmlResults);

                        var NewWindow = window.open("", "", "height=800,width=1000")
                        if (!NewWindow || NewWindow == null) {
                            ToastError("Print", "You must enable popups for this website. Make sure popups are not blocked.");
                            return;
                        }

                        NewWindow.document.write(sHtmlResults);
                        NewWindow.document.close();
                        NewWindow.focus();
                        NewWindow.print();
                        NewWindow.onfocus = function () { setTimeout(function () { NewWindow.close(); }, 2000); }

                        // Success!
                        return;
                    }
                }
            }

            /////////////////////////////////////////////////////////////////////////////////////////
            // Failed!
            // Fall back to this ugly solution when the app cannot export to html with base64 results
            /////////////////////////////////////////////////////////////////////////////////////////

            ToastError("Print", "Export to HTML failed. Using page contents.");

            var sSelectedHtmlContent = GetSelectedContentHtml();
            if (!sSelectedHtmlContent) {
                ToastError("Print", "This page cannot be printed");
                return;
            }

            var NewWindow = window.open("", "", "height=800,width=1000");
            if (!NewWindow || NewWindow == null) {
                ToastError("Print", "You must enable popups for this website. Make sure popups are not blocked.");
                return;
            }

            NewWindow.document.write(sSelectedHtmlContent);
            AddMainAppCssToDocument(NewWindow.document.head);
            NewWindow.document.close();
            NewWindow.focus();
            setTimeout(function () { NewWindow.print(); }, 1000);
            NewWindow.onfocus = function () { setTimeout(function () { NewWindow.close();
                    // Bad
                    //window.location.reload(); // ugly hack because something bad happens to javascript functions in window.location.reload();()
                }, 2000);
            }
        },
        error: function (xhr, status, error) {

            ClosePleaseWaitDialog();

            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxExportContent", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });

}


// Reads the SQL query from the current pane's hidden input and prints the Gantt chart for those tasks.
// Delegates all AJAX work to AjaxGetPrintableProjectTaskGanttFromSql().
function PrintProjectTaskGanttFromSql() {

    var sSqlScript = GetSelectedSqlScript();
    if (!sSqlScript) {
        ToastError("Print Gantt", "No SQL query found for the current view.");
        return;
    }

    AjaxGetPrintableProjectTaskGanttFromSql(GetSelectedContentType(), sSqlScript);
}


// Resolves the project from the currently selected record and prints the full Gantt chart for it.
// Delegates all AJAX work to AjaxGetPrintableProjectTaskGanttFromSelectedRecord().
function PrintProjectTaskGanttFromSelectedRecord() {

    AjaxGetPrintableProjectTaskGanttFromSelectedRecord(
        GetSelectedContentType(),
        GetSelectedRecordId(),
        GetSelectedRecordTableId(),
        GetSelectedDataType()
    );
}


// Posts the given SQL query to the server, receives a self-contained HTML Gantt document,
// and opens it in a print popup. The server runs the SQL, builds the chart, and returns
// the full HTML as data.HtmlResult.
function AjaxGetPrintableProjectTaskGanttFromSql(ContentType, sSqlScript) {

    // Show please-wait while the server queries tasks and builds the HTML
    OpenPleaseWaitDialog("Print Gantt");

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetPrintableProjectTaskGanttFromSql",
        type: "POST",
        data: JSON.stringify({ ContentType: ContentType, sSqlScript: sSqlScript }),
        contentType: "application/json",
        success: function (data) {

            ClosePleaseWaitDialog();

            // Surface any server-side error (bad SQL, empty result, etc.)
            if (!data.Success) { ToastError("Print Gantt", data.ErrorResults); return; }

            // Open a new window to hold the printable HTML document
            var win = window.open("", "", "height=800,width=1200");
            if (!win || win == null) { ToastError("Print Gantt", "You must enable popups for this website."); return; }

            // Write the self-contained HTML (includes all CSS inline) and trigger print
            win.document.write(data.HtmlResult);
            win.document.close();
            win.focus();
            win.print();

            // Auto-close the popup 2 seconds after the user returns focus to it
            win.onfocus = function () { setTimeout(function () { win.close(); }, 2000); };
        },
        error: function (xhr, status, error) {
            ClosePleaseWaitDialog();
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxGetPrintableProjectTaskGanttFromSql", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


// Posts the selected record identifiers to the server, which resolves the project ID,
// queries all project tasks, and returns a self-contained HTML Gantt document.
// Opens the result in a print popup.
function AjaxGetPrintableProjectTaskGanttFromSelectedRecord(ContentType, SelectedRecordId, SelectedTableId, SelectedDataType) {

    // Show please-wait while the server resolves the project and builds the HTML
    OpenPleaseWaitDialog("Print Gantt");

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetPrintableProjectTaskGanttFromSelectedRecord",
        type: "POST",
        data: JSON.stringify({
            ContentType:      ContentType,
            SelectedRecordId: SelectedRecordId,
            SelectedTableId:  SelectedTableId,
            SelectedDataType: SelectedDataType
        }),
        contentType: "application/json",
        success: function (data) {

            ClosePleaseWaitDialog();

            // Surface any server-side error (record not found, no project, etc.)
            if (!data.Success) { ToastError("Print Gantt", data.ErrorResults); return; }

            // Open a new window to hold the printable HTML document
            var win = window.open("", "", "height=800,width=1200");
            if (!win || win == null) { ToastError("Print Gantt", "You must enable popups for this website."); return; }

            // Write the self-contained HTML (includes all CSS inline) and trigger print
            win.document.write(data.HtmlResult);
            win.document.close();
            win.focus();
            win.print();

            // Auto-close the popup 2 seconds after the user returns focus to it
            win.onfocus = function () { setTimeout(function () { win.close(); }, 2000); };
        },
        error: function (xhr, status, error) {
            ClosePleaseWaitDialog();
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxGetPrintableProjectTaskGanttFromSelectedRecord", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}


