command -nargs=? -complete=dir DlcPro call s:ProjectSet('dlcpro-new', '<args>')
command -nargs=? -complete=dir DlcProOld call s:ProjectSet('dlcpro', '<args>')
command -nargs=? -complete=dir DlcProShg call s:ProjectSet('shg', '<args>')
command -nargs=? -complete=dir DlcProGui call s:ProjectSet('dlcpro-gui', '<args>')
command -nargs=? -complete=dir DlcProTui call s:ProjectSet('dlcpro-tui', '<args>')
command -nargs=? -complete=dir DlcProTuiSimulator call s:ProjectSet('dlcpro-tui-simulator', '<args>')
command -nargs=? -complete=dir DlcProCan call s:ProjectSet('dlcpro-can', '<args>')
command -nargs=? -complete=dir Topmode call s:ProjectSet('topmode', '<args>')
command -nargs=? -complete=dir TopmodeGui call s:ProjectSet('topmode-gui', '<args>')
command -nargs=? -complete=dir DigiFalc call s:ProjectSet('digifalc', '<args>')
command -nargs=? -complete=dir ServoBoard call s:ProjectSet('servoboard', '<args>')
command -nargs=? -complete=dir DlMotor call s:ProjectSet('dl-motor', '<args>')
command -nargs=? -complete=dir Pfd call s:ProjectSet('pfd', '<args>')
command -nargs=? -complete=dir Tiny call s:ProjectSet('tiny', '<args>')
command -nargs=? -complete=dir OperationPanelF1 call s:ProjectSet('operation-panel-f1', '<args>')
command -nargs=? -complete=dir OperationPanelF4 call s:ProjectSet('operation-panel-f4', '<args>')
command -nargs=? -complete=dir DeCoF call s:ProjectSet('decof', '<args>')
command DeviceFirmwareUpdate call s:DeviceFirmwareUpdate()
command -nargs=? -complete=file JenkinsLinter call s:Jenkins_linter('<args>')

" set titlestring=

" Get titlestring for DLCpro
function! g:Title_string()

    let titlestring = ''
    if exists('g:project_type')
        let titlestring .= ' project: '.g:project_type
    endif

    if exists('g:ProjectBuildDir')
        let cmakefile = g:ProjectBuildDir . '/CMakeCache.txt'
        if filereadable(cmakefile)
            let titlestring .= '    compiler: '
            for line in readfile(cmakefile)
                if match(line, 'NEW_COMPILER:BOOL=OFF') >= 0
                    let titlestring .= 'old'
                elseif match(line, 'NEW_COMPILER:BOOL=ON') >= 0
                    let titlestring .= 'new'
                endif
            endfor
        endif
    endif

    return titlestring
endfunction

function! s:ProjectSet(project_type, project_base_dir)
    set spell spelllang=en,de
    set expandtab
    set cinoptions=l1,g2,h2,N-2,t0,+0,(0,w1,Ws,m1,)100,*100
    set textwidth=120
    let $QT_FONT_DPI=96 " Size for qt-application in debugger

    let g:project_type = a:project_type
    let g:jenkins_url = 'http://jenkins.toptica.com'
    let s:ProjectBaseDir = fnamemodify(a:project_base_dir, ":p")

    " Direnv
    execute "DirenvExport"
    let $DIRENV_DIR = s:ProjectBaseDir

    " vim path
    execute 'cd '.s:ProjectBaseDir
    execute 'set path-=./**'
    execute 'set path+='.s:ProjectBaseDir.'**'

    " Settings for invoke
    let s:invoke = 'invoke'
    let s:tasks_file_dev = '~/tools/invoke/'.g:project_type.'/tasks.py'
    command! TasksLoad call system('cp '.s:tasks_file_dev.' tasks.py') " copy development version to project
    command! TasksSave call system('cp tasks.py '.s:tasks_file_dev) " copy project version to development
    " Tab-completion for invoke is done with plugin vim-bash-completion
    let $BASH_COMPLETION_DIR = '/home/liebl/.invoke'
    let invoke_completion_file = $BASH_COMPLETION_DIR.'/bash_completion'
    if !filereadable(invoke_completion_file)
        call system('invoke --print-completion-script bash > '.invoke_completion_file)
    endif

    " python tags
    " execute "set tags+=" . s:ProjectBaseDir . '/tags'

    " configure quickfix window for asyncrun
    augroup QuickfixStatus
        autocmd BufWinEnter quickfix setlocal 
                    \ statusline=%t\ [%{g:asyncrun_status}]\ %{exists('w:quickfix_title')?\ '\ '.w:quickfix_title\ :\ ''}\ %=%-15(%l,%c%V%)\ %P
    augroup END

    " ======
    " Invoke
    " ======

    compiler gcc
    let g:BuildType = 'Debug'
    function! s:getDefaultValueForOption(option_name)
        if a:option_name == '--project'
            return g:project_type
        elseif a:option_name == '--device-ip'
            return g:DeviceIP
        elseif a:option_name == '--build-type'
            return g:BuildType
        elseif a:option_name == '--laser1-type'
            return g:DeviceType
        elseif a:option_name == '--powerswitch-ip'
            return g:PowerswitchIP
        elseif a:option_name == '--powerplug'
            return g:Powerplug
        else
            return ""
        endif
    endfunction

    " Add default value for all available options, if not already set
    function! s:SetDefaultsForAllOptions(commandline)

        let commandline = a:commandline
        let task = split(commandline)[0]
        let l:tasks = system(s:invoke.' --list')

        if l:tasks =~ task
            let l:options_allowed = system(s:invoke.' --complete -- '.task.' -')
            for option in split(l:options_allowed)
                let value = s:getDefaultValueForOption(option)
                if value != '' && commandline !~ option
                    let commandline .= ' '.option.'='.value
                endif
            endfor
        endif

        return commandline
    endfunction

    " Tab completion for Invoke is done by bash-completion
    function! GetAllInvokeCompletions(ArgLead, CmdLine, CursorPos)
        let l:words = split(a:CmdLine)
        let l:words[0] = 'invoke'
        let l:command = join(l:words)
        return bash#complete(l:command)
    endfunction
    command! -complete=customlist,GetAllInvokeCompletions -nargs=* Invoke call s:Invoke('<args>', 'async')

    function! s:Invoke(args, async_mode)
        " Add defaults for options
        let l:options = s:SetDefaultsForAllOptions(a:args)

        if (a:async_mode == 'sync')
            " Synchronous execution with returned output
            let l:output = trim(system(s:invoke.' -e '.l:options))
            if l:output =~ 'No idea'
                return ''
            else
                return l:output
            endif
        elseif (a:async_mode == 'background')
            " Asynchronous execution in background
            call system(s:invoke.' -e '.l:options.'&')
        else
            " Asynchronous execution with AsyncRun
            call asyncrun#quickfix_toggle(10, 1)
            let &makeprg = s:invoke.' -e'
            execute 'AsyncRun -mode='.a:async_mode.' -save=2 -program=make @ '.l:options
        endif
    endfunction

    " Get some configurations from the project
    " ----------------------------------------
    let l:tasks = s:Invoke('--list', 'sync')
    let g:DebugRemote = (l:tasks =~ 'gdb-server')

    let g:ProjectBuildDir = s:Invoke('get-build-dir', 'sync')
    " Fallback
    if g:ProjectBuildDir == ''
        let g:ProjectBuildDir = s:ProjectBaseDir.'.build/'.g:project_type
    endif
    let g:Elffile = s:Invoke('get-elf-file', 'sync')

    let l:is_arm = s:Invoke('is-arm', 'sync')
    let g:termdebug_config = {}
    if l:is_arm =~ 'True'
        if g:project_type == 'topmode' || g:project_type == 'dlcpro'
            " Old dlcpro and topmode need old gdb
            let g:termdebug_config['command'] = '/opt/OSELAS.Toolchain-2020.08.0/arm-v7a-linux-gnueabihf/gcc-10.2.1-clang-10.0.1-glibc-2.32-binutils-2.35-kernel-5.8-sanitized/bin/arm-v7a-linux-gnueabihf-gdb'
        else
            let g:termdebug_config['command'] = 'arm-none-eabi-gdb'
        endif
    else
        let g:termdebug_config['command'] = ['gdb']
        " let g:termdebug_config['command'] = ['ssh', 'localhost', 'gdb']
    endif

    if (count(['dlcpro', 'dlcpro-new'], g:project_type) > 0)
        set wildignore-=**/firmware/src/device-control/**
        set wildignore+=**/shg-firmware/**
        set titlestring=%<%t\ (%{expand('%:p:h')})%{g:Title_string()}
        let g:DeviceIP = 'dlc_pro__040083'
        let g:DeviceType = 'TApro'
        let g:PowerswitchIP = 'elab-stefan'
        let g:Powerplug = '1'
        command! DlcProGuiStart execute("!~/dlcpro/pc-gui/start-gui&")
    elseif ((g:project_type == 'dlcpro-tui') || (g:project_type == 'dlcpro-tui-simulator'))
        " let s:Program = '/user-interface/src/user-interface'
        " let s:Elffile = s:Program
        " let g:ProgramRemote = '/opt/app/bin/user-interface'
        set wildignore-=**/firmware/src/device-control/**
        set wildignore+=**/shg-firmware/**
        let g:DeviceIP = 'dlc_pro__040083'
    elseif (g:project_type == 'dlcpro-can')
        " let s:Program = '/canopen/can-updater'
        " let s:Elffile = s:Program
        " let g:ProgramRemote = '/opt/app/bin/can-updater'
        set wildignore-=**/firmware/src/device-control/**
        set wildignore+=**/shg-firmware/**
        let g:DeviceIP = 'dlc_pro__040083'
    elseif (g:project_type == 'shg')
        " let s:Program = '/shg-firmware/device-control/device-control-shg'
        " let s:Elffile = s:Program
        " let g:ProgramRemote = '/opt/app/bin/device-control-shg'
        set wildignore-=**/shg-firmware/**
        set wildignore+=**/firmware/src/device-control/**
        let g:DeviceIP = 'dlc_pro__040083'
        " let g:DebugRemote = v:true
        " let g:GdbPort = '6666'
        " let g:SshOpts = '-o ForwardAgent=yes -o ProxyCommand="ssh -o RemoteCommand=none -q -W shg:22 root@%h" -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR'
        " let g:SshOpts2 = '-L localhost:1998:localhost:1998 -L localhost:1999:localhost:1999'
    elseif (g:project_type == 'topmode')
        let g:DeviceIP = 'topmode_stefan'
        let g:PowerswitchIP = 'elab-stefan'
        let g:Powerplug = '3'
        command! TopmodeGuiStart execute("!~/topmode/pc-gui/start-gui&")
    elseif (g:project_type == 'operation-panel-f1')
        let g:stm32_target = 'STM32F10X'
    elseif (g:project_type == 'operation-panel-f4')
        let g:stm32_target = 'STM32F4XX'
    endif

    function! s:DeviceFirmwareUpdate()
        call s:Invoke('kill', 'bang')
        call s:Invoke('flash', 'bang')
        call s:Invoke('run', 'bang')
    endfunction

    function! g:JLinkSWOviewer()
        let cmd = '/JLinkSWOViewerCLExe -device STM32H743ZI -itmmask 0xffffffff -swofreq 450000'
        call asyncrun#quickfix_toggle(10, 1)
        execute 'AsyncRun -mode=async @ ' . cmd
    endfunction

    function! s:SendToDebugger(command)
        call term_sendkeys('', a:command . "\n")
    endfunction

    function! s:StartDebugger(elffile, attach)
        if (a:attach == 0)
            Termdebug
        else
            execute 'Termdebug ' . a:elffile
        endif
    endfunction


    command! DeviceDebug call s:DeviceDebug(0)
    command! DeviceDebugAttach call s:DeviceDebug(1)
    function! s:DeviceDebug(attach)
        if g:DebugRemote
            call s:Invoke('kill', 'bang')
            " Close quickfix window
            execute 'cclose'
            autocmd! User TermdebugStartPre
            autocmd! User TermdebugStartPost
            autocmd! User TermdebugStopPost
            call s:Invoke('gdb-server', 'background')
            sleep 2
            let s:gdb_connect_script = g:ProjectBuildDir.'/gdbinit'
            if file_readable(s:gdb_connect_script)
                autocmd User TermdebugStartPost call term_sendkeys('',"source ".s:gdb_connect_script."\n")
            endif
            Termdebug
            call s:SendToDebugger('set confirm off')
            " Close Program window
            execute '2hide'
        else
            call s:StartDebugger(g:Elffile, a:attach)
            call s:SendToDebugger('file '.g:Elffile)
            " call s:SendToDebugger('break main')
            " call s:SendToDebugger('run')
        endif
    endfunction

    " ------
    " Pandoc
    " ------
    command! TopticaBeamer execute('!pandoc -s -t beamer -H toptica-style.tex -o %:r.pdf %')

    " -----------------
    " Jenkins validator
    " -----------------
    function! s:Jenkins_linter(jenkinsfile)
        if a:jenkinsfile == ''
            let jenkinsfile = expand("%")
        else
            let jenkinsfile = a:jenkinsfile
        endif

        if !filereadable(jenkinsfile)
            echoerr("File not found: ".jenkinsfile)
            return
        endif

        if !exists("s:user")
            let s:user = input("jenkins-user:")
        endif
        if !exists("s:passwd")
            let s:passwd = inputsecret("password:")
            echo "\n"
        endif
        let user_pass = s:user.":".s:passwd

        let l:out = system("curl --no-progress-meter --user '".user_pass."' -X POST -F 'jenkinsfile=<".jenkinsfile."' ".g:jenkins_url."/pipeline-model-converter/validate")
        if match(l:out, "HTTP ERROR 401") >= 0
            " Forget credentials on authorization error
            unlet s:user
            unlet s:passwd
        endif
        echo l:out
    endfunction
endfunction