import { UserInfo } from '../../../models/userInfo.model';
import { InnovationIdeaDetailsResponse, InnovationType } from 'app/models/InnovationIdea.model';
import { Idea, InnovationIdeaPayload, InnovationStatus, InnovationIdeaCreatePayload, InnovationIdeaUpdatePayload } from 'app/models/InnovationIdea.model';
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { LocalStorageService } from 'angular-2-local-storage';
import { EmployeeWizardService } from '../employee-wizard.service';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { isNumber } from 'util';
import { Observable } from 'rxjs/Observable';
import { ResponseCoInnovation } from 'app/models/coInnovation-response';
import { Subject } from 'rxjs/Rx';
import { ActivatedRoute, Router } from '@angular/router';
import { EmployeeFirstTimeActionsButtonsService, Action } from '../employee-first-time-actions-buttons.service';
import { PgUserInfoMstr } from 'app/models/user/user.model';
import { InnovationHttpService } from 'app/services/innovation/innovation-http.service';

@Component({
  selector: 'app-employee-wizard-innovation',
  templateUrl: './employee-wizard-innovation.component.html',
  styleUrls: ['./employee-wizard-innovation.component.scss']
})
export class EmployeeWizardInnovationComponent implements OnInit {
  ideaPayload: InnovationIdeaUpdatePayload;
  private sub: any;
  innovationDataLoaded = false;
  innovationType: InnovationType = InnovationType.idea;
  labels = {
    idea: { title: 'idea', inputs: { title: 'Title', desc: 'Description' }},
    poc: { title: 'POC', inputs: { title: 'POC Title', desc: 'POC Description' }}
  };

  innovationStatus: InnovationStatus;
  activeButton = 'create';

  innovationFocal$: Observable<{ focalId: number; focalName: string; pgUserInfoMstr: PgUserInfoMstr; createdBy: string; createdDate: number; updatedBy: string; updatedDate: number; }[]>;
  AssigncoInnovation: ResponseCoInnovation[];

  coInnovators: { text: string, value: number }[] = [];
  coInnovation: ResponseCoInnovation[];
  innovationCategories$: Observable<[{ categoryId: number; category: string; createdBy: string; createdDate: any; updatedBy: string; updatedDate: any; }]>;
  coInnovSelected: any;
  public view_InnovationFormModel: FormGroup;
  public currentUser: UserInfo;

  public innovationToUpdate: Idea;
  public uploadedFileId: number;
  public selectedFileName: string;

  isUpdate = false;

  @ViewChild('files') files: ElementRef;
  @ViewChild('submit') submit: ElementRef;
  constructor(
    private employeeWizardService: EmployeeWizardService,
    private employeeHttpService: EmployeeHttpService,
    private innovationHttpService: InnovationHttpService,
    private localStorageService: LocalStorageService,
    private toast: ToastsManager,
    private actionsButtons: EmployeeFirstTimeActionsButtonsService,
    private router: Router,
    private route: ActivatedRoute,
  ) {
    const defaultDefinition = { disabled: false, value: '' };
    this.view_InnovationFormModel = new FormGroup({
      title: new FormControl(defaultDefinition, [Validators.required]),
      category: new FormControl(defaultDefinition, [Validators.required]),
      description: new FormControl(defaultDefinition, [Validators.required]),
      coIinnovators: new FormControl([]),
      innovationFocal: new FormControl(defaultDefinition, [Validators.required])
    });
  }

  ngOnInit() {
    this.employeeWizardService.setCurrentPage(3);
    this.currentUser = this.localStorageService.get('userInfo');
    // Check if the user requested a POC's form.
    if (this.route.snapshot.url.length > 1 && this.route.snapshot.url[1].path === InnovationType.poc) {
      this.innovationType = InnovationType.poc;
    }
    this.sub =  this.route.params.subscribe(params => {
      if (params['id'] !== undefined) {
        this.innovationHttpService.getInnovationDetails(+params['id'])
        .subscribe((response: InnovationIdeaDetailsResponse) => {
          this.innovationToUpdate = response.ideasList[0];
          this.checkAccess();
          this.innovationDataLoaded = true;
        }, error => this.toast.error('There was an error, please refresh the page.'));
      } else {
        this.innovationDataLoaded = true;
      }
    });
  }

  checkAccess() {
    // Get innovation coinnovators
    const ideaOwners = this.innovationToUpdate.coInnovators.map(innovator => {
      return innovator.id;
    });
    // Add innovation creator
    ideaOwners.push(this.innovationToUpdate.creator.id);

    const isEditable = this.innovationToUpdate.status === InnovationStatus.Rework ||this.innovationToUpdate.status === InnovationStatus.Created || this.innovationToUpdate.status === InnovationStatus.Submitted;
    const userHasPermission = ideaOwners.includes(this.currentUser.userInfoMstrId);
    if (isEditable && userHasPermission) {
      this.innovationDataLoaded = true;
    } else {
      const message = isEditable ? 'You are not allowed to edit this Innovation.' : 'This Innovation is read only.';
      this.toast.error(message);
    }
  }
}
