
<kiss-container class="kiss-margin-small" size="medium">

    <ul class="kiss-breadcrumbs">
        <li><a href="<?=$this->route('/system')?>"><?=t('Settings')?></a></li>
    </ul>

    <vue-view>

        <template>

            <div class="kiss-margin-large-bottom kiss-size-3 kiss-text-bold">
                <?=t('Sync')?>
            </div>

            <?=$this->render('sync:views/partials/menu.php')?>

            <div v-if="runner.running">

                <strong class="kiss-text-caption"><?=t('Running sync job')?>:</strong>

                <app-scrollcontainer class="kiss-margin-small-top kiss-padding kiss-bgcolor-contrast">

                    <pre class="kiss-size-small kiss-color-muted kiss-text-monospace">{{runner.log || (runner.finished ? t('Finished without meaningful output'):'')}}</pre>

                    <div class="kiss-margin-small kiss-color-muted" v-if="!runner.finished">
                        <app-loader mode="dots" size="small" class="kiss-margin-remove"></app-loader>
                    </div>

                </app-scrollcontainer>
            </div>

            <div v-if="!runner.running">

                <div class="kiss-text-caption kiss-margin" v-if="active.length">{{ t('Selected jobs') }}</div>

                <div class="kiss-padding-larger kiss-size-3 kiss-align-center kiss-color-muted kiss-margin-large" v-if="!active.length">
                    {{ t('No sync jobs selected') }}
                </div>

                <kiss-grid class="kiss-margin-large-bottom" cols="2@s 4@m" gap="small" v-if="active.length">

                    <kiss-card class="kiss-padding animated flipInX" theme="bordered shadowed contrast" v-for="job in active" :key="job.name">
                        <div class="kiss-flex kiss-flex-middle">
                            <div class="kiss-color-primary kiss-margin-small-end"><kiss-svg :src="$baseUrl(job.icon || 'sync:icon.svg')" width="25" height="25"></kiss-svg></div>
                            <div class="kiss-text-bold kiss-flex-1 kiss-text-capitalize">{{ job.label || job.name }}</div>
                            <a class="kiss-margin-small-start" :class="{'kiss-color-warning': !job.syncSettings.syncAll}" @click="configJob=job" v-if="job.fields && job.fields.length"><icon>tune</icon></a>
                            <a class="kiss-margin-small-start kiss-color-danger" @click="job._active=false"><icon>do_not_disturb_on</icon></a>
                        </div>
                    </kiss-card>

                </kiss-grid>

                <div class="kiss-margin-large" v-if="inactive.length">

                    <div class="kiss-text-caption kiss-margin">{{ t('Available sync jobs') }}</div>

                    <kiss-card class="kiss-padding kiss-flex kiss-flex-middle kiss-margin-xsmall kiss-cursor-pointer" gap="small" theme="contrast" hover="bordered-primary" v-for="job in inactive" :key="job.name" @click="job._active = true">
                        <kiss-svg class="kiss-color-muted" :src="$baseUrl(job.icon || 'sync:icon.svg')" width="25" height="25"></kiss-svg>
                        <div class="kiss-color-muted kiss-text-capitalize kiss-flex-1">{{ job.label || job.name }}</div>
                        <a class="kiss-size-4"><icon>add_circle</icon></a>
                    </kiss-card>

                </div>

            </div>
            <teleport to="body">

                <app-actionbar>

                    <kiss-container class="kiss-padding kiss-flex" size="medium" :class="{'kiss-disabled': !active.length}" v-if="!runner.running">

                        <div class="kiss-position-relative">
                            <div class="kiss-text-upper" style="font-size:9px">{{ t('Sync target') }}</div>
                            <div class="kiss-margin-small-top kiss-color-muted kiss-size-4" v-if="!targets.length">
                                {{ t('No sync targets available') }}
                            </div>
                            <div class="kiss-margin-small-top kiss-size-4" :class="{'kiss-color-muted':!target, 'kiss-text-bold':target}" v-if="targets.length">
                                {{ target ? target.name : t('Select target') }}
                            </div>
                            <a class="kiss-cover" kiss-popout="#select-target" v-if="targets.length"></a>
                        </div>

                        <div class="kiss-margin-start" v-if="target">
                            <div class="kiss-text-upper" style="font-size:9px">{{ t('Sync mode') }}</div>
                            <div class="kiss-margin-small-top kiss-overlay-input">
                                <span class="kiss-size-4 kiss-flex kiss-flex-middle kiss-text-capitalize" v-if="target.mode"><icon class="kiss-margin-small-end">sync</icon> {{ target.mode || ''}}</span>
                                <span class="kiss-size-4 kiss-flex kiss-flex-middle kiss-color-muted" v-if="!target.mode"><icon class="kiss-margin-small-end">sync</icon> {{ t('Select mode') }}</span>
                                <select v-model="target.mode">
                                    <option></option>
                                    <option value="pull" v-if="target.modes.pull">PULL</option>
                                    <option value="push" v-if="target.modes.push">PUSH</option>
                                </select>
                            </div>
                        </div>

                        <div class="kiss-flex-1"></div>

                        <button class="kiss-button kiss-button-primary" :class="{'kiss-disabled': !target || !target.mode}" @click="sync">
                            {{ t('Start sync') }}
                        </button>

                    </kiss-container>

                    <kiss-container class="kiss-padding kiss-flex kiss-flex-middle" size="medium" v-if="runner.running">

                        <div class="kiss-flex-1">
                            <app-loader size="small" class="kiss-margin-remove" v-if="!runner.finished"></app-loader>
                        </div>

                        <button class="kiss-button kiss-button-primary" @click="cancelSync" v-if="!runner.finished">
                            {{ t('Cancel sync') }}
                        </button>

                        <button class="kiss-button kiss-button-primary" @click="resetRunner" v-if="runner.finished">
                            <icon class="kiss-margin-xsmall-end">check</icon> {{ t('Job finished') }}
                        </button>
                    </kiss-container>

                </app-actionbar>

                <kiss-dialog open="true" size="large" v-if="configJob">
                    <kiss-content class="animated fadeInUp faster">

                        <div class="kiss-text-bold kiss-text-capitalize kiss-margin">
                            {{ configJob.label || configJob.name }}
                        </div>

                        <div class="kiss-margin kiss-flex kiss-flex-middle">
                            <div class="kiss-margin-small-end"><field-boolean v-model="configJob.syncSettings.syncAll"></field-boolean></div>
                            <div class="kiss-color-muted kiss-text-capitalize">{{ t('Sync all') }}</div>
                        </div>

                        <kiss-card class="kiss-padding kiss-margin" theme="contrast bordered" style="max-height:50vh;overflow:auto;" v-if="!configJob.syncSettings.syncAll && configJob.fields && configJob.fields.length">
                            <fields-renderer class="kiss-margin" v-model="configJob.syncSettings" :fields="configJob.fields"></fields-renderer>
                        </kiss-card>

                        <div class="kiss-margin kiss-flex kiss-flex-end">

                            <a class="kiss-button" @click="configJob=null">
                                {{ t('Close') }}
                            </a>

                        </div>
                    </kiss-content>
                </kiss-dialog>

                <kiss-popout id="select-target">
                    <kiss-content>
                        <kiss-navlist class="kiss-margin">
                            <ul>
                                <li class="kiss-nav-header"><?=t('Select target')?></li>
                            </ul>

                            <ul class="kiss-overflow-y-auto" style="max-height:250px;">
                                <li v-for="t in targets">
                                    <kiss-card class="kiss-padding-xsmall kiss-flex kiss-flex-middle kiss-position-relative" hover="contrast">
                                        <div class="kiss-margin-xsmall-end kiss-size-6"><icon>adjust</icon></div>
                                        <div>{{ t.label || t.name}}</div>
                                        <a class="kiss-cover" @click="target=t"></a>
                                    </kiss-card>
                                </li>

                            </ul>
                        </kiss-navlist>

                        <button type="button" class="kiss-button kiss-button-small kiss-width-1-1 kiss-margin-small-top" kiss-popout-close><?=t('Close')?></button>
                    </kiss-content>
                </kiss-popout>

            </teleport>

        </template>

        <script type="module">

            export default {

                data() {

                    let jobs = Object.values(<?=json_encode($jobs)?>);

                    jobs.forEach(job => {
                        job.syncSettings = {
                            syncAll:true
                        };
                    });

                    let targets = <?=json_encode($targets)?>;
                    let target = targets.length === 1 ? targets[0] : null;

                    if (target && Object.values(target.modes).filter(v => v).length === 1) {
                        target.mode = target.modes.pull ? 'pull' : 'push';
                    }

                    return {
                        runner: {
                            running: <?=json_encode($isRunning)?>,
                            finished: false,
                            log: ''
                        },
                        logIdle: null,
                        targets,
                        jobs,
                        target,
                        configJob: null
                    }
                },

                mounted() {
                    if (this.runner.running) {
                        this.startLog();
                    }
                },

                computed: {
                    active() {
                        return this.jobs.filter(job => job._active === true).sort((a, b) => a[a.label ? 'label':'name'].localeCompare(b[b.label ? 'label':'name']));
                    },
                    inactive() {
                        return this.jobs.filter(job => !job._active).sort((a, b) => a[a.label ? 'label':'name'].localeCompare(b[b.label ? 'label':'name']));
                    }
                },

                methods: {

                    sync() {

                        let config = {
                            target: this.target,
                            jobs: this.active
                        };

                        this.$request('/sync/run', {config}).then(rsp => {
                            this.runner.running = true;
                            this.runner.finished = false;
                            this.startLog();
                        });
                    },

                    cancelSync() {

                        App.ui.confirm('Are you sure?', () => {

                            this.$request('/sync/reset').then(rsp => {
                                //
                            });
                        });
                    },

                    startLog() {

                        if (this.logIdle) {
                            clearInterval(this.logIdle);
                        }

                        this.logIdle = setInterval(() => {

                            this.$request('/sync/getSyncLog').then(rsp => {

                                const finished = !rsp.log;

                                this.runner.finished = finished;

                                if (finished) {
                                    clearInterval(this.logIdle);
                                    App.ui.notify('Sync finished!');
                                } else {
                                    this.runner.log = rsp.log;
                                }
                            });
                        }, 1000);
                    },

                    resetRunner() {

                        if (this.logIdle) clearInterval(this.logIdle);

                        Object.assign(this.runner, {
                            running: false,
                            finished: false,
                            log: ''
                        });
                    }
                }

            }
        </script>

    </vue-view>
</kiss-container>
