import {Component, Input, OnInit, ViewChild} from '@angular/core';
import {AlertController, ModalController} from '@ionic/angular';
import {EditorService} from '../../service/editor.service';
import {PageVersionRecord} from '../../structures/PageRecord';
import {EditorPage} from '../../pages/editor/editor.page';

@Component({
    selector: 'app-version-modal',
    templateUrl: './version-modal.component.html',
    styleUrls: ['./version-modal.component.scss'],
})
export class VersionModalComponent implements OnInit {
    @Input() pageId: string;
    @ViewChild('editor') editor: EditorPage;

    public pageVersions: PageVersionRecord[] = [];
    public selectedVersion?: PageVersionRecord;

    constructor(
        protected alerts: AlertController,
        protected modals: ModalController,
        protected editorService: EditorService,
    ) {
        console.log('version modal', this);
    }

    async ngOnInit() {
        this.pageVersions = await this.editorService.loadPageVersions(this.pageId);
        this.onVersionClick(this.pageVersions[0]);
    }

    dismiss(reload = false) {
        this.modals.dismiss(reload);
    }

    async revertToVersion() {
        const alert = await this.alerts.create({
            header: 'Revert page?',
            message: `This will revert the current version of the page to version ${this.selectedVersion.versionNum}. Continue?`,
            buttons: [
                {
                    text: 'Keep It',
                    role: 'cancel',
                },
                {
                    text: 'Revert It',
                    handler: async () => {
                        await this.editorService.revertPageToVersion(this.pageId, this.selectedVersion.versionNum);
                        this.dismiss(true);
                    },
                },
            ],
        });

        await alert.present();
    }

    async onVersionClick(version: PageVersionRecord) {
        this.selectedVersion = version;
        setTimeout(() => {
            if ( this.editor ) {
                this.editor.ionViewDidEnter();
            }
        }, 300);
    }
}
