const branchs = loadBranches;

$(function()
{
    if($('#artifactList tbody').children('tr').length > 0)
    {
        $('#artifactList').removeClass('hidden')
        $('[name=scmPath]').closest('.form-row').addClass('hidden');
        $('[name=filePath]').closest('.form-row').addClass('hidden');
        $('#buildFiles').closest('.form-row').addClass('hidden');
    }
    else
    {
        $('#artifactList').addClass('hidden');
    }

    setTimeout(getArtifactRepoByProduct, 100);
});

window.unlinkArtifact = function(dom)
{
    if(typeof buildLang === 'undefined') return;
    zui.Modal.confirm(
    {
        message: buildLang.unlinkArtifactConfirm, icon:'icon-exclamation-sign', iconClass: 'warning-pale rounded-full icon-2x'
    }).then((res) =>
    {
        if(res)
        {
            $(dom).closest('tr').remove();

            if($('#artifactList tbody tr').length < 1)
            {
                $('#artifactList').addClass('hidden');
                $('[name=scmPath]').closest('.form-row').removeClass('hidden');
                $('[name=filePath]').closest('.form-row').removeClass('hidden');
                $('#buildFiles').closest('.form-row').removeClass('hidden');
            }
        }
    });
};

window.mouseEvent = function(event, dom)
{
    $('.unlink-action').addClass('hidden')
    if(event === 'enter') $(dom).find('.unlink-action').removeClass('hidden')
};

window.loadBranches = function(productID)
{
    branchs(productID);
    getArtifactRepoByProduct(productID);
};

window.getArtifactRepoByProduct = function(productID)
{
    productID = parseInt(productID);
    if(!productID) productID = $('input[name=product]').val();
    if(!productID) return;
    $.get($.createLink('artifactrepo', 'ajaxGetArtifactRepoByProduct', 'productID=' + productID), function(data)
        {
            if(data.length > 0)
            {
                $('.artifactrepo').removeClass('hidden');
            }
            else
            {
                $('.artifactrepo').addClass('hidden');
            }
        }, 'json');
};

window.selectArtifact = function()
{
    productID = $('input[name=product]').val();
    zui.Modal.open({url: $.createLink('build', 'linkArtifact', 'productID=' + productID), size: 'sm'})
};

window.showLinkArtifacts = function(showLinkArtifacts, unlinkBtnTitle)
{
    const artifacts = JSON.parse(showLinkArtifacts);
    if(artifacts)
    {
        $('#artifactList').removeClass('hidden')
        $('[name=scmPath]').closest('.form-row').addClass('hidden');
        $('[name=filePath]').closest('.form-row').addClass('hidden');
        $('#buildFiles').closest('.form-row').addClass('hidden');
    }

    artifacts.forEach(function(artifact)
    {
        if(!artifact) return;
        $('#artifactList').find('tr').each(function()
        {
            if($(this).hasClass('artifact-' + artifact.id)) $(this).remove();
        });

        $('#artifactList tbody').append(
            `<tr class="cursor-pointer artifact-link-list artifact-${artifact.id}">` +
            `<td title="${artifact.name}">` +
            `<i class="icon icon-stack mr-1"></i>${artifact.name}` +
            `<input type="hidden" class="artifact-${artifact.id}" name="artifacts[${artifact.repo}][${artifact.id}][name]" value="${artifact.name}" />` +
            `<input type="hidden" class="artifact-path" name="artifacts[${artifact.repo}][${artifact.id}][path]" value="${artifact.path}" />` +
            `<input type="hidden" class="artifact-type-${artifact.id}" name="artifacts[${artifact.repo}][${artifact.id}][type]" value="${artifact.type}" />` +
            `<button class="ml-2 unlink-action hidden text-primary ajax-submit ghost unlink-btn" title="${unlinkBtnTitle}"><i class="icon icon-unlink"></i></button>` +
            `</td></tr>`
        );
    });
};

window.clickOnLinkArtifact = function()
{
    const repoID = $('[name=artifactRepo]').val();
    const linkArtifacts = $('#filesTree').zui('tree').$.getChecks();
    if(linkArtifacts.length == 0) return;

    linkArtifacts.forEach(function(linkArtifact)
    {
        const asset = $('#filesTree').zui('tree').$.getItem(linkArtifact);
        if(typeof asset == 'undefined' || asset.kind == 'dir') return;

        const assetID    = asset.repoType == 'gitfox' ? asset.metadata.node_id : asset.assetID;
        const inputClass = asset.repoType == 'gitfox' ? 'linkArtifact-' + assetID.replace(/\./g, '-') : 'linkArtifact-' + assetID;
        const assetName  = asset.repoType == 'gitfox' && asset.format == 'container' ? `${asset.repoName}/${asset.metadata.name}:${asset.metadata.version}` : asset.text;

        $('#linkArtifact').append(`<input type="hidden" class="${inputClass}" name="artifacts[${repoID}][${assetID}][text]" value="${assetName}" />`);
        $('#linkArtifact').append(`<input type="hidden" class="${inputClass}" name="artifacts[${repoID}][${assetID}][path]" value="${asset.id}" />`);

        if(asset.repoType == 'gitfox')
        {
            $('#linkArtifact').append(`<input type="hidden" class=${inputClass} name="artifacts[${repoID}][${assetID}][format]" value="${asset.format}" />`);
        }
    });
};

window.loadArtifact = function(repo)
{
    $('#linkArtifact .toolbar').closest('.form-row').addClass('no-label form-actions form-group center is-pinned');
    $('#linkArtifact .toolbar').removeClass('no-label form-actions form-group');
    const repoID = repo ? repo : $('[name=artifactRepo]').val();
    const link = $.createLink('build', 'artifactTree', 'repoID=' + repoID);

    $('#artifactTree').load(link);
};

window.treeClick = function(info)
{
    $.cookie.set('artifactDir', info.item.path);
};
