
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Project Assistant functions
// Create new projects, duplicate projects, add tasks to projects
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Open the Project Assistant dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
var bProjectAssistantDialogIsOpen = false;
function OpenProjectAssistantDialog() {

    // Fill the property grid in the dialog with record properties
    ProjectCreator = {};
    FillProjectAssistantControls();
    AjaxRefreshProjectAssistantContent($("#ProjectAssistantStartTabDiv"));

    var nDlgWidth = 800;
    var nDlgHeight = 600;
    var nWindowWidth = $(window).width();
    var nWindowHeight = $(window).height();
    if (nWindowWidth < nDlgWidth)
        nDlgWidth = nWindowWidth * 0.95;
    if (nWindowHeight < nDlgHeight)
        nDlgHeight = nWindowHeight * 0.95;

    // Open the dialog
    // igniteui.com/help/igdialog-property-reference
    $("#igDialogProjectAssistant").igDialog({ modal: true, headerText: "Project Assistant", width: nDlgWidth, height: nDlgHeight, resizable: true, closeOnEscape: true, openAnimation: "", closeAnimation: "fade"/*, openAnimation: "fade"*/ });
    $("#igDialogProjectAssistant").igDialog("open");

    CenterDialog("igDialogProjectAssistant");

    // Set up controls
    bProjectAssistantDialogIsOpen = true;
    $("#ProjectAssistantTabs").tabs("option", "active", 0);
}




/**
 * Call Ajax function to fill content section of any Assistant
 * The DIV must contain a "data-assistant-panel" attribute with a value to pass to the Home Controller
 * @param {any} divelement
 */
function AjaxRefreshProjectAssistantContent(divElement) {

    if (!divElement)
        return;

    var data_assistant_panel = $(divElement).attr("data-assistant-panel");
    if (!data_assistant_panel)
        return;

    var params = {
        "AssistantPanel": data_assistant_panel,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxGetAssistantPartialView/",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json", /*type of data sent to server*/
    }).done(function (data) {
        $(divElement).html(data);

        //ResizeDialogToWindowSize("igDialogProjectAssistant");
        CenterDialog("igDialogProjectAssistant");

        // Get an object used to initialize values
        //AjaxGetProjectCreatorObject();

        // Enable or disable controls based on choices
        FillProjectAssistantControls();
        EnableProjectAssistantControls();
    });
}



var ProjectCreator = {};


function AjaxProjectAssistantFinish() {

    // Convert parameters to a JSON string because MVC binding is not reliable
    var params = {
        "ProjectCreator": ProjectCreator,
    };
    var ParamsJsonString = JSON.stringify(params);
    params = {
        "ProjectCreatorJsonString": ParamsJsonString,
    };

    $.ajax({
        url: VirtualDirectory + "/Home/AjaxProjectAssistantFinish",
        type: "POST",
        data: JSON.stringify(params),
        contentType: "application/json",
        success: function (response) {
            if (response.Success) {
                if (response.ProjectAssistantError) {
                    // Project assistant error
                    ShowProjectAssistantError(response.ProjectAssistantError);
                }
                else {
                    CloseProjectAssistantDialog();

                    // Show project tasks for the newly created project
                    if (response.FilterJsonString) {
                        ShowProjectTaskGridViewWithFilter(response.FilterJsonString);
                        return;
                    }

                    // Show the project task view to see the new tasks
                    ShowProjectTaskGridView();
                }
            }
            else {
                // Error
                ToastError("AjaxProjectAssistantFinish", response.ErrorResults);
            }
        },
        error: function (xhr, status, error) {
            var errormsg = "Error " + xhr.status + ", " + xhr.statusText;
            ToastError("AjaxGetProjectCreatorObject", errormsg);
            console.log('AJAX: ' + errormsg);
        }
    });
}



/**
 * A project assistant tab was clicked
 * https://api.jqueryui.com/tabs/#option-active
 * @param {any} event
 * @param {any} ui
 */
function OnProjectAssistantTabActivate(event, ui) {

//    ui
//    Type: Object
//    newTab
//    Type: jQuery
//        oldTab
//    Type: jQuery
//        newPanel
//    Type: jQuery
//        oldPanel
//    Type: jQuery

    if (!ui)
        return;
    if (!ui.newPanel)
        return;

    var NewTabId = ui.newPanel.attr("id");
    if (!NewTabId)
        return;

    // Collect the current control values
    CollectProjectAssistantValues();

    // Fill the property grid in the dialog with record properties
    AjaxRefreshProjectAssistantContent(ui.newPanel);

    //alert("OnProjectAssistantTabActivate: " + ui.newTab);
}


function GetActiveProjectAssistantTab() {

    // https://api.jqueryui.com/tabs/#option-active
    var idxTab = $("#ProjectAssistantTabs").tabs("option", "active");
    return idxTab;
}

function ActivateNextProjectAssistantTab(bNext) {

    // https://api.jqueryui.com/tabs/#option-active
    var idxTab = GetActiveProjectAssistantTab();
    if (bNext)
         idxTab++;
    else idxTab--;
    if (idxTab < 0)
        idxTab = 0;

    // Activate a tab
    $("#ProjectAssistantTabs").tabs("option", "active", idxTab);
}

function GetNumProjectAssistantTabs() {

    var nTabs = $('#ProjectAssistantTabs >ul >li').length;
    return nTabs;
}

function ShowProjectAssistantError(sError) {

    $("#ProjectAssistantFinishError").css('visibility', 'visible');
    $("#ProjectAssistantFinishError").html(sError);
}


//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Next, Back, Finish
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function OnProjectAssistantBack() {

    CollectProjectAssistantValues();
    ActivateNextProjectAssistantTab(false/*bNext*/);
}

function OnProjectAssistantNext() {

    CollectProjectAssistantValues();
    ActivateNextProjectAssistantTab(true/*bNext*/);
}

function OnProjectAssistantLastTab() {

    var nTabs = GetNumProjectAssistantTabs();

    // Activate a tab
    $("#ProjectAssistantTabs").tabs("option", "active", nTabs-1);
}

function OnProjectAssistantFinish() {

    // Activate the last tab (in case it was not already activated)
    CollectProjectAssistantValues();
    OnProjectAssistantLastTab();

    // Try to create the project now
    // An error will be displayed if failed
    //setTimeout(function () { AjaxProjectAssistantFinish() }, 250);
    AjaxProjectAssistantFinish();
}






//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Html events from controls
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//


function OnProjectAssistantDuplicateRadioButton(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantDuplicateRadioButton: " + Id);
    EnableProjectAssistantControls();
}

function OnProjectAssistantCreateRadioButton(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantCreateRadioButton: " + Id);
    EnableProjectAssistantControls();
}

function OnProjectAssistantAddToRadioButton(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantAddToRadioButton: " + Id);
    EnableProjectAssistantControls();
}

function OnProjectAssistantDuplicateDropdownChanged(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantDuplicateDropdownChanged: " + Id);
    EnableProjectAssistantControls();
}

function OnProjectAssistantAddToDropdownChanged(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantAddToDropdownChanged: " + Id);
    EnableProjectAssistantControls();
}




function OnProjectAssistantClientBillableChecked(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantClientBillableChecked: " + Id);
    EnableProjectAssistantControls();
}

function OnProjectAssistantClientExistingRadioButton(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantClientExistingRadioButton: " + Id);
    EnableProjectAssistantControls();
}

function OnProjectAssistantClientNewRadioButton(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantClientNewRadioButton: " + Id);
    EnableProjectAssistantControls();
}

function OnProjectAssistantExistingClientDropdownChanged(element) {

    //var Id = $(element).attr("id");
    //alert("OnProjectAssistantDuplicateDropdownChanged: " + Id);
    EnableProjectAssistantControls();
}




/**
 * Collect all the values from html controls
 * Pass these values to the server to create the project and all associated records
 * */
function CollectProjectAssistantValues() {

    var bProjectAssistantDuplicate = IsControlChecked("ProjectAssistantDuplicate");
    var bProjectAssistantCreate = IsControlChecked("ProjectAssistantCreate");
    var bProjectAssistantAddTo = IsControlChecked("ProjectAssistantAddTo");
    var bProjectAssistantClientExisting = IsControlChecked("ProjectAssistantClientExisting");
    var bProjectAssistantClientNew = IsControlChecked("ProjectAssistantClientNew");

    //CREATEMETHOD { DUPLICATE=0, NEW=1, USEEXISTING=2 }
    ProjectCreator.CreateProjectMethod = 0;
    ProjectCreator.CreateClientMethod = 0;
    ProjectCreator.sDuplicateFromProjectId = "";
    ProjectCreator.sExistingProjectId = "";
    ProjectCreator.sNewProjectName = "";
    ProjectCreator.sProjectTaskNames = "";
    ProjectCreator.sExistingClientId = "";
    ProjectCreator.sNewClientName = "";
    ProjectCreator.bBillable = false;

    // Duplicate, Create, Add to existing project
    if (bProjectAssistantDuplicate)
        ProjectCreator.CreateProjectMethod = 0;
    else if (bProjectAssistantCreate)
        ProjectCreator.CreateProjectMethod = 1;
    else if (bProjectAssistantAddTo)
        ProjectCreator.CreateProjectMethod = 2;

    // Existing client, create new client
    if (bProjectAssistantClientExisting)
        ProjectCreator.CreateClientMethod = 2;
    else if (bProjectAssistantClientNew)
        ProjectCreator.CreateClientMethod = 1;

    // Project
    ProjectCreator.sDuplicateFromProjectId = $("#ProjectAssistantDuplicateDropdown").find(":selected").val();
    ProjectCreator.sExistingProjectId = $("#ProjectAssistantAddToDropdown").find(":selected").val();
    ProjectCreator.sNewProjectName = $("#ProjectAssistantCreateProjectTextbox").val();

    // Task names
    ProjectCreator.sProjectTaskNames = $("#ProjectAssistantTaskTextArea").val();

    // Client
    ProjectCreator.sExistingClientId = $("#ProjectAssistantExistingClientDropdown").find(":selected").val();
    ProjectCreator.sNewClientName = $("#ProjectAssistantCreateClientTextbox").val();
    ProjectCreator.bBillable = $("#ProjectAssistantClientBillable").is(':checked');
}


function FillProjectAssistantControls() {

    // Project
    //CREATEMETHOD { DUPLICATE=0, NEW=1, USEEXISTING=2 }
    if (ProjectCreator.CreateProjectMethod == 0 || !ProjectCreator.CreateProjectMethod)
        $("#ProjectAssistantDuplicate").prop("checked", true);
    else if (ProjectCreator.CreateProjectMethod == 1)
        $("#ProjectAssistantCreate").prop("checked", true);
    else if (ProjectCreator.CreateProjectMethod == 2)
        $("#ProjectAssistantAddTo").prop("checked", true);
    if (ProjectCreator.sDuplicateFromProjectId)
        $("#ProjectAssistantDuplicateDropdown").val(ProjectCreator.sDuplicateFromProjectId);
    if (ProjectCreator.sExistingProjectId)
        $("#ProjectAssistantAddToDropdown").val(ProjectCreator.sExistingProjectId);
    $("#ProjectAssistantCreateProjectTextbox").val(ProjectCreator.sNewProjectName);

    // Client
    if (ProjectCreator.CreateClientMethod == 1)
        $("#ProjectAssistantClientNew").prop("checked", true);
    else if (ProjectCreator.CreateProjectMethod == 2 || !ProjectCreator.CreateClientMethod)
        $("#ProjectAssistantClientExisting").prop("checked", true);
    if (ProjectCreator.sExistingClientId)
        $("#ProjectAssistantExistingClientDropdown").val(ProjectCreator.sExistingClientId);
    $("#ProjectAssistantCreateClientTextbox").val(ProjectCreator.sNewClientName);
    $("#ProjectAssistantClientBillable").prop("checked", ProjectCreator.bBillable);

    // Tasks
    var bProjectAssistantDuplicate = IsControlChecked("ProjectAssistantDuplicate");
    $("#ProjectAssistantTasksWillDuplicateMsg").css('visibility', bProjectAssistantDuplicate ? 'visible' : 'hidden');
    $("#ProjectAssistantTaskNamesLabel").css('visibility', bProjectAssistantDuplicate ? 'hidden' : 'visible');
    $("#ProjectAssistantTaskTextArea").css('visibility', bProjectAssistantDuplicate ? 'hidden' : 'visible');
    $("#ProjectAssistantTaskTextArea").val(ProjectCreator.sProjectTaskNames);
}


/**
 * Enable or disable controls
 * */
function EnableProjectAssistantControls() {

    // Step 1: Project
    var bProjectAssistantDuplicate = IsControlChecked("ProjectAssistantDuplicate");
    var bProjectAssistantCreate = IsControlChecked("ProjectAssistantCreate");
    var bProjectAssistantAddTo = IsControlChecked("ProjectAssistantAddTo");
    EnableControl("ProjectAssistantDuplicateDropdown", bProjectAssistantDuplicate);
    EnableControl("ProjectAssistantCreateProjectTextbox", bProjectAssistantCreate);
    EnableControl("ProjectAssistantAddToDropdown", bProjectAssistantAddTo);

    // Step 3: Client
    var bProjectAssistantClientExisting = IsControlChecked("ProjectAssistantClientExisting");
    var bProjectAssistantClientNew = IsControlChecked("ProjectAssistantClientNew");
    EnableControl("ProjectAssistantExistingClientDropdown", bProjectAssistantClientExisting);
    EnableControl("ProjectAssistantCreateClientTextbox", bProjectAssistantClientNew);
}

function IsControlChecked(elementid) {

    if (!elementid)
        return false;
    var element = $("#" + elementid);
    if (!element)
        return false;

    return element.is(':checked');
}

function EnableControl(elementid, bEnabled) {

    if (!elementid)
        return;
    var element = $("#" + elementid);
    if (!element)
        return;

    var bDisabled = !bEnabled;
    element.prop("disabled", bDisabled);
}



//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Project Tasks


function OnKeyUpProjectAssistantTaskTextArea(event) {


    // Display a list of existing project tasks in a dropdown
    // User can choose from these existing tasks
    CheckUpdateAndOpenTaskHintComboBox();
}


function OnKeyDownProjectAssistantTaskTextArea(event) {

    if (event.key !== "Tab")
        return;

    event.preventDefault();

    var oTextArea = document.getElementById("ProjectAssistantTaskTextArea");
    var nStart = oTextArea.selectionStart;
    var nEnd = oTextArea.selectionEnd;

    oTextArea.value = oTextArea.value.substring(0, nStart) + "\t" + oTextArea.value.substring(nEnd);
    oTextArea.selectionStart = oTextArea.selectionEnd = nStart + 1;
}


function CheckUpdateAndOpenTaskHintComboBox() {

    var sTextAtCurrentLine = GetEditLineTextAtTaskTextBox();
    if (!sTextAtCurrentLine || sTextAtCurrentLine == null || sTextAtCurrentLine.length == 0) {
        CloseTaskHintComboBox();
        return;
    }

    FillTaskHintComboBox();
    CheckOpenTaskHintComboBox();
}


/**
 * Get the text of the current line of the Tasks TextArea
 * This is the text where the caret is, starting at the beginning of the line
 * @returns
 */
function GetEditLineTextAtTaskTextBox() {

    // Get indexes where the caret is
    var nStartOfLineIdx = GetStartOfLineIndex();
    var nSelectionStart = $("#ProjectAssistantTaskTextArea").get(0).selectionStart;
    if (nStartOfLineIdx < 0)
        return "";
    if (nSelectionStart < 0)
        return "";
    if (nStartOfLineIdx > nSelectionStart)
        return "";

    // Get just the text of this line
    var sFullText = $("#ProjectAssistantTaskTextArea").val();
    var sTextAtCurrentLine = sFullText.substring(nStartOfLineIdx, nSelectionStart);
    return sTextAtCurrentLine;
}

function GetStartOfLineIndex() {
    var selectionStart = $("#ProjectAssistantTaskTextArea").get(0).selectionStart;
    var text = $("#ProjectAssistantTaskTextArea").val();

    // Find the last newline character before the selectionStart
    var lastNewlineIndex = text.lastIndexOf('\n', selectionStart - 1);

    // If no newline is found (it's the first line), the start of the line is 0
    // Otherwise, it's the index of the newline + 1 (to move past the newline character)
    return (lastNewlineIndex === -1) ? 0 : lastNewlineIndex + 1;
}

function ReplaceTaskTextAtLineIndex(sReplaceText) {

    $("#ProjectAssistantTaskTextArea").focus();

    var nStartOfLineIdx = GetStartOfLineIndex();
    var nSelectionStart = $("#ProjectAssistantTaskTextArea").get(0).selectionStart;
    if (nStartOfLineIdx < 0)
        return "";
    if (nSelectionStart < 0)
        return "";
    if (nStartOfLineIdx > nSelectionStart)
        return "";

    var sFullText = $("#ProjectAssistantTaskTextArea").val();
    var sTextAtCurrentLine = sFullText.substring(nStartOfLineIdx, nSelectionStart);
    if (!sTextAtCurrentLine || sTextAtCurrentLine == null || sTextAtCurrentLine.length == 0)
        return;

    // Replace the line text with the replacement text
    var sBeginText = sFullText.substring(0, nStartOfLineIdx);
    var sAfterText = "";
    if (nSelectionStart < sFullText.length)
        sAfterText = sFullText.substring(nSelectionStart, sFullText.length);
    var sNewFullText = sBeginText + sReplaceText + sAfterText;
    $("#ProjectAssistantTaskTextArea").val(sNewFullText);

    // Set the new selectionStart to be just after the replacement text
    var nNewSelectionStart = sBeginText.length + sReplaceText.length;
    $("#ProjectAssistantTaskTextArea").get(0).selectionStart = nNewSelectionStart;
    $("#ProjectAssistantTaskTextArea").get(0).selectionEnd = nNewSelectionStart;
}

function FillTaskHintComboBox() {

    var sTextAtCurrentLine = GetEditLineTextAtTaskTextBox();
    if (!sTextAtCurrentLine || sTextAtCurrentLine == null || sTextAtCurrentLine.length == 0)
        return;

    AjaxQueryStartsWith("ProjectTasks"/*DbTableName*/, sTextAtCurrentLine, OnQueryStartsWithCallback/*successcallback*/);
}

function OnQueryStartsWithCallback(DbTableName, sFindPartialName, CsvNames) {

    if (!CsvNames)
        return;

    //ToastMessage("OnQueryStartsWithCallback", CsvNames);
    //OpenTaskHintItemsPopupMenu($("#ProjectAssistantTaskTextPopupDiv"), DbTableName, sFindPartialName, CsvNames);
    CreatePopupForCsvList($("#ProjectAssistantTaskTextPopupDiv"), CsvNames, "OnClickTaskHintItem"/*OnItemClickFunction*/);
}



/**
 * A popup item was clicked
 * See CreatePopupForCsvList() popup function
 * @param {any} evt
 * @param {any} sItemName
 * @param {any} sItemId
 */
function OnClickTaskHintItem(evt, sItemName, sItemId) {

    //ToastMessage("OnClickTaskHintItem", sItemName);

    ReplaceTaskTextAtLineIndex(sItemName)

    // Close the popup
    CloseLastPopup();
}




function CheckOpenTaskHintComboBox() {

}

/**
 * Close the dropdown containing project task names
 */
function CloseTaskHintComboBox() {
    CloseLastPopup();
}

//////////////////////////////////////////////////////////////////////////////////////////
// OLD: This works, but doesn't provide DISTINCT project task names
//function OpenTaskHintItemsPopupMenu(ElementObj) {

//    if (!ElementObj)
//        return;
//    if (!ElementObj.length)
//        return;

//    var sTextAtCurrentLine = GetEditLineTextAtTaskTextBox();
//    if (!sTextAtCurrentLine || sTextAtCurrentLine == null || sTextAtCurrentLine.length == 0)
//        return;

//    var FilterObject = {
//        "Starts with": sTextAtCurrentLine,
//        "DISTINCT": "true",
//        "SELECTCOLUMNS": "ProjectTasks.[Name], ProjectTasks.GUID",
//    };
//    var FilterJsonString = JSON.stringify(FilterObject);

//  //CreatePopupForRecordsetList(ElementObj, PopupDivIdPrefix, TableName, RecordId, OnItemClickFunction, PerformMenuAction, IfListIsEmptyFunction, FilterJsonString) {
//    CreatePopupForRecordsetList(ElementObj, "PopupListDiv-TaskHintItems-", "ProjectTasks"/*sDbTable*/, ""/*RecordId*/, "OnClickTaskHintItem", null/*PerformMenuAction*/, null/*IfListIsEmptyFunction*/, FilterJsonString);
//}
//////////////////////////////////////////////////////////////////////////////////////////






//////////////////////////////////////////////////////////////////////////////////////////
// OLD: This was replaced with a general purpose CreatePopupForCsvList() function
//function OpenTaskHintItemsPopupMenu(ElementObj, DbTableName, sFindPartialName, CsvNames) {

//    if (!ElementObj)
//        return;
//    if (!ElementObj.length)
//        return;

//    // Build the popup which will contain a list of record items to choose from
//    var PopupDiv = CreatePopupDiv(ElementObj, "PopupListDiv-TaskHintItems-"/*PopupDivIdPrefix*/);
//    if (!PopupDiv) {
//        ToastError("Popup", "Hmm, something went wrong creating the popup!");
//        return;
//    }

//    AjaxGetCsvItemsInPopupList(event, null/*element*/, PopupDiv, CsvNames, "OnClickTaskHintItem"/*OnItemClickFunction*/);
//}
//////////////////////////////////////////////////////////////////////////////////////////




//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
// Close the dialog
//\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\////\\//
function CloseProjectAssistantDialog() {
    $("#igDialogProjectAssistant").igDialog("close");
    bProjectAssistantDialogIsOpen = false;
}

function IsProjectAssistantDialogOpen() {
    return bProjectAssistantDialogIsOpen;
}




