<?php
namespace zin;

$jsRoot = $app->getWebRoot() . 'js/';
h::importCss($jsRoot . 'range/range.css');

$clientLang = $app->getClientLang();
$isAuthor   = $project->createdBy == $this->app->user->account;

jsVar('clientLang', $clientLang);
jsVar("dataframe",  $dataframe);
jsVar('analysisID', $analysisID);
jsVar('hasPriv',    $isAuthor);
jsVar('lang', $lang);
jsVar('copySuccess', $lang->perfproject->copySuccess);
jsVar('copyFailed',  $lang->perfproject->notes->copyFailed);

$products      = $this->loadModel('product')->getPairs('nodeleted', 0, '', 0);
$executions    = $this->loadModel('execution')->getPairs();
$tasks         = $this->loadModel('task')->getAllParisForPerf();
$hasStory      = hasPriv('product', 'browse');
$hasBug        = hasPriv('bug', 'browse');
$hasExecution  = hasPriv('project', 'execution');
$hasTask       = hasPriv('execution', 'task');
$hasExecutions = empty($products) && !empty($executions);
$hasTasks      = empty($products) && empty($executions) && !empty($tasks);
$noData        = empty($products) && empty($executions) && empty($tasks);
$noStoryBug    = !$hasStory && !$hasBug;
$showExecution = !empty($executions) && $noStoryBug && $hasExecution;
$noOthers      = !$hasStory && !$hasBug && !$hasExecution;
$showTask      = !empty($tasks) && $hasTask && $noOthers;
$showCreate    = $noOthers && !$hasTask;

$createLink = '';
if(!empty($products) && $hasStory)             $createLink = createLink('product', 'browse', "productID=0&branch=all&browseType=&param=0&storyType=story&orderBy=&recTotal=0&recPerPage=20&pageID=1&projectID=0&from=perf&blockID=$analysisID");
if(!empty($products) && !$hasStory && $hasBug) $createLink = createLink('bug', 'browse', "productID=0&branch=&browseType=&param=0&orderBy=&recTotal=0&recPerPage=20&pageID=1&from=perf&blockID=$analysisID");
if($hasExecutions || $showExecution)           $createLink = createLink('project', 'execution', "status=undone&projectID=0&orderBy=order_asc&productID=0&recTotal=1&recPerPage=100&pageID=1&queryID=0&from=perf&blockID=$analysisID");
if($hasTasks || $showTask)                     $createLink = createLink('execution', 'task', "execution=0&status=unclosed&param=0&orderBy=&recTotal=0&recPerPage=100&pageID=1&from=perf&blockID=$analysisID");
if($noData || $showCreate)                     $createLink = createLink('perfproject', 'create', "analysisID=$analysisID&type=upload");

$fnGenerateNavs = function() use ($lang, $project, $analysisID, $isAuthor)
{
    $canRename  = common::hasPriv('perfanalysis', 'rename');
    $canDelete  = common::hasPriv('perfanalysis', 'delete');
    $totalCount = count($project->analysisList);

    $navs = array();
    foreach($project->analysisList as $currentIndex => $analysis)
    {
        $currentIndex++;
        $navActionItems = array();
        if($canRename || $canDelete)
        {
            if($canRename) $navActionItems[] = array('text' => $lang->perfproject->analysis->rename, 'url' => $this->createLink('perfanalysis', 'rename', "analysisID={$analysis->id}"), 'data-toggle' => 'modal', 'data-size' => 'sm');
            if(count($project->analysisList) > 1) $navActionItems[] = array('text' => $lang->perfproject->analysis->delete, 'url' => $this->createLink('perfanalysis', 'delete', "analysisID={$analysis->id}&projectID=$project->id&currentID=$analysisID"), 'innerClass' => 'ajax-submit', 'data-confirm' => $this->lang->perfanalysis->confirmDelete);
        }

        $navs[] = div
        (
            setClass('h-8 flex'),
            div(setClass('overflow-hidden relative analysis-actions-btn'), setStyle(array('border-top-left-radius' => '6px', 'border-top-right-radius' => '6px')), setData(array('id' => $analysis->id)), btn(set::text($analysis->name), set::hint($analysis->name), setStyle(array('padding-right' => '20px', '--tw-ring-color' => 'var(--color-canvas-rgb)', 'border-bottom-left-radius' => '0', 'border-bottom-right-radius' => '0')), $analysis->id == $analysisID ? null : array(setStyle('background-color', 'var(--zt-page-bg)'), set::url($this->inlink('analysis', "analysisID={$analysis->id}"))), setClass('w-24 shadow-none analysis-name', $analysis->id == $analysisID ? 'text-primary' : '')), !$isAuthor ? null : dropdown
            (
                set::key($analysis->id),
                btn(setClass('dropdown-btn shadow-none absolute right-0 top-0 z-10 opacity-0 w-5'), setStyle(array('box-shadow' => 'none', '--tw-ring-color' => 'var(--color-canvas-rgb)', 'border-top-left-radius' => '0', 'border-bottom-left-radius' => '0', 'border-bottom-right-radius' => '0')), set::icon('ellipsis-v'), set::caret(false)),
                set::trigger('hover'),
                set::menuClass('menu-analysis-actions analysis_' . $analysis->id),
                set::items($navActionItems),
                set::hasIcons(true)
            )),
            $currentIndex < $totalCount ? div(setClass('divider h-4 mt-2 mx-1')) : null
        );
    }
    return  $navs;
};

featureBar
(
    to::trailing
    (
        setClass('relative'),
        div
        (
            setClass('flex items-center absolute left-0 gap-1'),
            setStyle(array('bottom' => '-1.75rem')),
            btn
            (
                setClass('text-primary'),
                set::iconClass('text-lg'),
                set::type('ghost'),
                set::icon('menu-my'),
                set::url($this->inlink('browse')),
                set::hint($lang->perfproject->browse)
            ),
            $fnGenerateNavs,
            $isAuthor ? array(
                div(setClass('divider h-4 mt-2')),
                btn
                (
                    set::type('ghost'),
                    set::icon('plus'),
                    count($project->analysisList) >= $config->perfanalysis->maxCount ? array(
                        set::disabled(true),
                        set::hint($lang->perfanalysis->createLimitTip),
                    ) : array(
                        set::hint($lang->perfanalysis->add),
                        set::url($this->createLink('perfanalysis', 'create', "projectID={$project->id}")),
                        setData(array('toggle' => 'modal', 'size' => 'sm'))
                    )
                )
            ) : null
        )
    )
);

$fnGenerateMethodBtns = function() use ($config, $lang, $analysisID)
{
    $methods = array();
    foreach($lang->perfanalysis->methodTypes as $type => $typeName)
    {
        $btns = array();
        foreach($lang->perfanalysis->methods->{$type} as $method => $methodName)
        {
            $url = createLink('perfanalysis', 'addmethod', "analysisID=$analysisID&method=$method");
            $customs = $config->perfanalysis->customs;
            if(isset($customs[$method])) $url = createLink($customs[$method]['module'], $customs[$method]['method']['create'], "analysisID=$analysisID");
            $btns[] = li
            (
                btn(setClass('w-32 gray-500-pale text-fore shadow-none method-btn'), $methodName, set('data-toggle', 'modal'), set::url($url))
            );
        }
        $methods[] = ul
        (
            setClass(array('nav col w-36 gap-4', $type)),
            set('data-type', $type),
            li
            (
                setClass('heading w-32 text-center font-bold text-gray h-10 col justify-end'),
                $typeName
            ),
            $btns
        );
        $methods[] = div(setClass('divider'));
    }

    return $methods;
};

!$isAuthor ? toolbar(setClass('h-8')) : toolbar
(
    // btn
    // (
    //     set::type('ghost'),
    //     set::icon('export'),
    //     $lang->export
    // ),
    btn
    (
        set::type('ghost'),
        set::icon('refresh'),
        $lang->perfproject->analysis->refresh,
        on::click('refreshAll')
    ),
    dropdown
    (
        set::caret(false),
        set::trigger('hover'),
        set::placement('bottom-end'),
        to('trigger', btn
        (
            set::type('primary'),
            set::icon('plus'),
            $lang->perfanalysis->method
        )),
        to('menu', menu
        (
            setClass('dropdown-menu overflow-y-auto'),
            div
            (
                setClass('flex row pt-10 methods-btns'),
                $fnGenerateMethodBtns()
            )
        ))
    )
);

$fnGenerateMethods = function() use ($lang, $config, $methods, $isAuthor)
{
    if(empty($methods)) return;

    $htmls = array();
    foreach($methods as $method)
    {
        $actions = array();
        $actions[] = array('type' => 'ghost', 'size' => 'sm', 'icon' => 'caret-up', 'hint' => $lang->perfproject->analysis->reduce, 'class' => 'analysis-method-collapse text-gray', 'onclick' => 'window.toggleCollapse(this)');
        if($isAuthor)
        {
            $settingUrl = createLink('perfanalysis', 'editmethod', "methodID=$method->id");
            $customs = $config->perfanalysis->customs;
            $methodName = $method->name;
            if(isset($customs[$methodName])) $settingUrl = createLink($customs[$methodName]['module'], $customs[$methodName]['method']['setting'], "methodID=$method->id");

            $actions[] = array('type' => 'ghost', 'size' => 'sm', 'icon' => 'refresh',  'hint' => $lang->refresh, 'class' => 'analysis-method-refresh text-gray', 'onclick' => 'window.refreshMethod(this)');
            $actions[] = array('type' => 'ghost', 'size' => 'sm', 'icon' => 'controls', 'hint' => $lang->perfproject->analysis->setting, 'data-toggle' => 'modal', 'url' => $settingUrl);
            $actions[] = array('type' => 'ghost', 'size' => 'sm', 'icon' => 'copy',     'hint' => $lang->perfproject->analysis->copy, 'class' => 'method-copy-all text-gray', 'onclick' => 'window.onCopyMethod(this)');
            $actions[] = array('type' => 'ghost', 'size' => 'sm', 'icon' => 'trash',    'hint' => $lang->perfproject->analysis->deleteMethod, 'class' => 'text-gray ajax-submit', 'url' => createLink('perfanalysis', 'deletemethod', "methodID=$method->id"), 'data-confirm' => $lang->perfanalysis->confirmDelete);
        }

        $htmls[] = panel
        (
            setID('method' . $method->id),
            setClass('border-b'),
            setdata(array('methodid' => $method->id)),
            set::titleClass('inline-block text-ellipsis'),
            set::titleProps(array('title' => $method->title)),
            set::title($method->title),
            set::headingActions($actions),
            div
            (
                setClass('analysis-method-results block-collapse collapse in'),
                html($this->perfanalysis->buildMethodResult($method->results, $method->id, false, 0, $isAuthor))
            )
        );
    }

    return $htmls;
};

$fnGenerateDataSource = function() use ($dataframe)
{
    $cols = array();
    foreach($dataframe->columns as $index => $title)
    {
        $cols[] = array('title' => $title, 'name' => 'C' . ($index + 1), 'width' => $dataframe->colWidths[$index]);
    }
    return array('cols' => $cols, 'data' => $dataframe->data);
};

sidebar(set::width('40%'), set::minWidth('16%'), set::maxWidth('40%'), set::showToggle(false), set::toggleBtn(false), setClass('bg-canvas px-3 py-2'), div
(
    setClass('h-8 pb-1 flex items-center justify-between'),
    div
    (
        setClass('flex items-center gap-1 text-gray'),
        icon('table-large'),
        span(setClass('text-fore font-semibold'), setStyle(array('min-width' => '28px')), $lang->perfproject->data),
        span(count($dataframe->data) . 'x' . count($dataframe->columns))
    ),
    $isAuthor && common::hasPriv('perfproject', 'create') ? btn(setStyle(array('box-shadow' => 'none')), set::icon('plus'), set::text($lang->perfanalysis->addData), setData(array('toggle' => 'modal', 'size' => 'lg')), set::url($createLink)) : null
), dtable
(
    setID('dataframe' . $analysisID),
    set::datasource($fnGenerateDataSource()),
    set::height(jsRaw('window.calculateHeight')),
    set::rowHeight(28),
    set::defaultColWidth(75),
    set::scrollbarSize(15),
    set::horzScrollbarPos('inside'),
    set::editable($isAuthor),
    set::ignoreDeselectOn('.contextmenu'),
    set::plugins(array('datagrid', 'contextmenu')),
    set::colResize(true),
    set::responsive(true),
    set::minRows(30),
    set::minCols(20),
    set::extraRows(5),
    set::extraCols(5),
    set::history(true),
    set::historyEnabled(true),
    set::datagridHotkeys(array('delete' => 'Delete')),
    // set::historyTarget('applied'),
    set::onHistoryApplied(jsRaw('window.handleHistoryApplied')),
    $isAuthor ? set::afterStageDraft(jsRaw('window.handleDataframeChange')) : null,
    $isAuthor ? set::contextmenu(jsRaw('window.dtableContextMenu')) : null,
    set::onColResize(jsRaw('window.onColResize')),
    set::onReadClipboardFail(jsRaw('window.onReadClipboardFail')),
    set::onRenderHeaderCell(jsRaw('window.onRenderHeaderCell')),
    set::onRenderCell(jsRaw('window.onRenderCell'))
), on::inited()->call('window.initDataframe'));
empty($methods) ? center
(
    setClass('h-full bg-canvas overflow-x-auto'),
    col
    (
        !$isAuthor ? null : div
        (
            setClass('row methods-btns'),
            $fnGenerateMethodBtns()
        )
    )
) : div
(
    setClass('analysis-methods bg-canvas'),
    setData(array('analysisID' => $analysisID)),
    $fnGenerateMethods()
);
