import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Editor } from 'primeng/editor';
import { Subscription } from 'rxjs/Subscription';

import { AppService } from '../../app.service';
import { ASSOCS } from '../../constants';
import { JobApplicationModel } from "../../models/job-application.model";
import { IframeMsgHandlingService } from '../../oneit/services/iframe-msg-handling.service';
import { SaveService } from '../../oneit/services/save.service';
import { UtilsService } from '../../oneit/services/utils.service';
import { AdminPortalLayoutService } from '../admin-portal/admin-portal-layout/admin-portal-layout.service';
import { BaseComponent } from '../admin-portal/base/base.component';
import { MessageEngineApplicantViewService } from './message-engine-applicant-view.service';

import { EngineApplicantView } from './message-engine-applicant-view.model';

@Component({
    selector: 'app-message-engine-applicant-view',
    templateUrl: './message-engine-applicant-view.component.html',
    styleUrls: ['./message-engine-applicant-view.component.scss']
})
export class MessageEngineApplicantViewComponent extends BaseComponent implements OnInit {

    @Input() embedded = false;
    subscriptions: Array<Subscription> = [];
    @ViewChild('form') form: NgForm;
    @ViewChild('message') messageEditor: Editor;
    createdObjs = {};
    updatedObjs = {};
    deletedObjs = {};

    engineApplicantView = new EngineApplicantView();
    jobApplication = new JobApplicationModel();
    showLoader = false;

    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private utilsService: UtilsService,
        private saveService: SaveService,
        private appService: AppService,
        private messageEngineApplicantViewService: MessageEngineApplicantViewService,
        private iframeMsgHandlingService: IframeMsgHandlingService,
        private adminPortalLayoutService: AdminPortalLayoutService
    ) {
        super(utilsService);
    }

    ngOnInit(): void {
        this.utilsService.resetCounter();
        this.setEditorClass();
        this.showLoader = true;
        this.subscriptions.push(this.activatedRoute.params
            .subscribe(
                (params: Params) => {
                    this.showLoader = true;
                    if (params.jobId) {
                        this.getEngineApplicantViewByID(params.jobId);
                    } else {
                        this.utilsService.createObject(this.engineApplicantView, this.createdObjs);
                        this.showLoader = false;
                    }
                }
            ));
    }

    getEngineApplicantViewByID(jobId: string): void {

        this.showLoader = true;
        this.utilsService.resetCounter();
        this.utilsService.clearErrorMessages();

        const assocs = [ASSOCS.JOB, [ASSOCS.CANDIDATE, ASSOCS.USER].join('.')];
        this.subscriptions.push(this.messageEngineApplicantViewService.getEngineApplicantViewByID(jobId, assocs)
            .subscribe(
                data => {
                    console.log(data);
                    this.engineApplicantView = data;
                    this.updatedObjs[this.engineApplicantView.ObjectID] = this.engineApplicantView;

                    // Loop over other multirefs here, which can be updated on screen e.g

                    this.showLoader = false;
                },
                error => {
                    this.showLoader = false;
                    this.utilsService.handleError(error);
                }
            )
        );
    }

    saveEngineApplicantView(reload: boolean): void {
        this.utilsService.clearErrorMessages();

        if (this.form.invalid) {
            this.utilsService.showAllErrorMessages();
        } else {
            this.showLoader = true;
            this.subscriptions.push(this.saveService.saveObjectsWithDefaultSvc(this.createdObjs, this.updatedObjs, this.deletedObjs)
                .subscribe(
                    data => {
                        this.utilsService.handleSuccess();
                        if (reload) {
                            let idToNavigate = this.engineApplicantView.ObjectID;
                            if (data.created[idToNavigate]) {
                                idToNavigate = data.created[idToNavigate];
                                this.router.navigate(['/message-engine-applicant-view', idToNavigate]);

                                return;
                            }
                            this.getEngineApplicantViewByID(idToNavigate);
                        } else {
                            this.router.navigate(['']);
                        }
                    },
                    error => {
                        this.showLoader = false;
                        this.utilsService.handleError(error);
                    }
                )
            );
        }
    }

    setEditorClass(): void {
        setTimeout(() => {
            const editElement = this.messageEditor.getQuill().container;

            if (!editElement) {
                return;
            }

            const editor = editElement.getElementsByClassName('ql-editor');

            if (!editor[0]) {
                return;
            }

            editor[0].classList.add('form-control');
            editor[0].classList.add('editor');

        }, 0);
    }
}
