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

import { AppService } from '../../app.service';
import { ResponseActionEnum } from '../../models/responseAction.enum';
import { StageTypeEnum } from '../../models/stageType.enum';
import { StepTypeEnum } from '../../models/stepType.enum';
import { WorkflowTemplateModel } from '../../models/workflowTemplate.model';
import { SaveService } from '../../oneit/services/save.service';
import { UtilsService } from '../../oneit/services/utils.service';
import { BaseComponent } from '../base/base.component';
import { EditWorkflowTemplateService } from './edit-workflow-template.service';

import { WorkflowTemplate } from './edit-workflow-template.model';

@Component({
    selector: 'app-edit-workflow-template',
    templateUrl: './edit-workflow-template.component.html'
})
export class EditWorkflowTemplateComponent extends BaseComponent implements OnInit {

    subscriptions: Array<Subscription> = [];
    @ViewChild('form') form: NgForm;
    createdObjs = {};
    updatedObjs = {};
    deletedObjs = {};

    workflow = new WorkflowTemplateModel();
    stageTypes: Array<StageTypeEnum>;
    stepTypes: Array<StepTypeEnum>;
    responseActions: Array<ResponseActionEnum>;
    editField: any = {};
    showLoader = false;
    editMode = false;

    workflowTemplate = new WorkflowTemplate();
    s: Array<any> = [];
    messagetemplates: Array<any> = [];
    messagetemplate_withdraws: Array<any> = [];
    Capture_CVs = [];
    Mandatory_CVs = [];
    Capture_Cover_Letters = [];
    Mandatory_cover_letters = [];
    Automatically_progress_to_next_stages = [];
    Use_messagings = [];

    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private utilsService: UtilsService,
        private saveService: SaveService,
        private appService: AppService,
        private editWorkflowTemplateService: EditWorkflowTemplateService
    ) {
        super(utilsService);
    }

    ngOnInit(): void {
        this.createdObjs = {};
        this.updatedObjs = {};
        this.deletedObjs = {};
        this.utilsService.resetCounter();
        this.showLoader = true;

        this.subscriptions.push(this.activatedRoute.params
            .subscribe(
                (params: Params) => {
                    this.showLoader = true;
                    this.getStageTypes();
                    this.getStepTypes();
                    this.getResponseActions();
                    if (params.id && params.id !== '0') {
                        this.editMode = true;
                        this.getWorkflowTemplateByID(params.id);
                    } else {
                        this.utilsService.createObject(this.workflow, this.createdObjs);
                        this.setDefaults();
                        this.showLoader = false;
                    }
                }
            ));
        this.gets();
    }

    setDefaults(): void {
        this.workflow.TemplateName = 'Workflow Template';
        this.workflow.LandingButtonText = 'Apply Now';
        this.workflow.VerificationHeaderText = 'Please verify your identity before applying to:';
        this.workflow.ThankYouHeaderText = 'Thank You for your application to:';
        this.workflow.ThankYouSecondaryText = 'We will get in touch with you soon';
        this.workflow.ApplicationButtonText = 'Submit';
        this.workflow.CaptureCV = true;
    }

    getStageTypes(): void {
        this.subscriptions.push(
            this.appService.getTypes('StageTypes')
                .subscribe((types: Array<StageTypeEnum>) => {
                    this.stageTypes = types;
                })
        );
    }

    getStepTypes(): void {
        this.subscriptions.push(
            this.appService.getTypes('StepTypes')
                .subscribe((types: Array<StepTypeEnum>) => {
                    this.stepTypes = types;
                })
        );
    }

    getResponseActions(): void {
        this.subscriptions.push(
            this.appService.getTypes('ResponseActions')
                .subscribe((types: Array<ResponseActionEnum>) => {
                    this.responseActions = types;
                })
        );
    }

    showLabel(id: string): boolean {
        return (this.editField[id] === undefined || this.editField[id] === false);
    }

    showInput(id: string): boolean {
        return this.editField && !!this.editField[id];
    }

    toggleInput(event, fieldName, save = true): void {
        this.utilsService.clearErrorMessages();
        if (event.type === 'blur') {
            if (!this.form.controls[fieldName].invalid) {
                this.editField[fieldName] = false;
                if (save) {
                    // save call to be sent
                }
            } else {
                this.utilsService.showAllErrorMessages();
            }
        } else {
            this.editField[fieldName] = true;
            setTimeout(() => {
                try {
                    document.getElementById(`${fieldName}Id`)
                        .focus();
                    document.getElementById(`${fieldName}Id`)
                        .getElementsByTagName('input')[0]
                        .focus();
                } catch (e) {
                    // ignore this.
                }
            }, 0);
        }
    }

    gets(): void {
        this.subscriptions.push(this.editWorkflowTemplateService.getDummy456s([])
            .subscribe(
                data => {
                    this.s = data;
                },
                error => {
                    this.utilsService.handleError(error);
                }
            )
        );
    }

    autoCompleteMessagetemplate(event): void {
        this.subscriptions.push(this.editWorkflowTemplateService.getmessagetemplatesForAutocomplete(event.query, [])
            .subscribe(
                data => {
                    for (const obj of data) {
                        // If you need to display anything complex in autocomplete label, put that code here
                        // e.g. obj.Name = obj.FirstName + ' ' + obj.LastName. So that you can use "Name" attribute in HTML
                    }
                    this.messagetemplates = data;
                },
                error => {
                    this.utilsService.handleError(error);
                }
            )
        );
    }

    autoCompleteMessagetemplate_withdraw(event): void {
        this.subscriptions.push(this.editWorkflowTemplateService.getmessagetemplate_withdrawsForAutocomplete(event.query, [])
            .subscribe(
                data => {
                    for (const obj of data) {
                        // sd
                    }
                    this.messagetemplate_withdraws = data;
                },
                error => {
                    this.utilsService.handleError(error);
                }
            )
        );
    }

    getWorkflowTemplateByID(id): void {

        this.showLoader = true;
        this.createdObjs = {};
        this.updatedObjs = {};
        this.deletedObjs = {};
        this.utilsService.resetCounter();
        this.utilsService.clearErrorMessages();

        this.subscriptions.push(this.editWorkflowTemplateService.getWorkflowTemplateByID(id, [])
            .subscribe(
                data => {
                    this.workflowTemplate = data;
                    this.updatedObjs[this.workflowTemplate.ObjectID] = this.workflowTemplate;

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

    saveWorkflowTemplate(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.workflowTemplate.ObjectID;
                            if (data.created[idToNavigate]) {
                                idToNavigate = data.created[idToNavigate];
                                this.router.navigate(['/edit-workflow-template', idToNavigate]);

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