import { Component, OnInit, Injectable, Inject, Output, EventEmitter } from '@angular/core';
import { LocalStorageService } from 'angular-2-local-storage';
import { FormControl, Validators, FormGroup } from '@angular/forms';
import {MAT_DIALOG_DATA, MatDialogRef} from '@angular/material';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';

@Injectable()
@Component({
  selector: 'app-employee-create-project',
  templateUrl: './employee-create-project.component.html',
  styleUrls: ['./employee-create-project.component.scss']
})
export class EmployeeCreateProjectComponent implements OnInit {

  createProjectForm: FormGroup;
  error: boolean;
  errMsg: string;
  projectDetails;
  techStacks;
  teckStack;
  interfaceOptions;
  prjResult;
  currentUser;
  template;
  gitUserDetail;
  defaultInterface;

  @Output() prjSubmitted = new EventEmitter();
  constructor(private employeeService: EmployeeHttpService, public dialogRef: MatDialogRef<EmployeeCreateProjectComponent>,
    @Inject(MAT_DIALOG_DATA) public dialogData: any, protected localStorageService: LocalStorageService) {
      this.currentUser = this.localStorageService.get('userInfo');
      this.techStacks = dialogData.projectTechStacks;
      this.gitUserDetail = dialogData.gitUserDetail;
      console.log('dialogData', dialogData);
  }

  ngOnInit() {
    this.createProjectForm = new FormGroup({
      techStack: new FormControl('', Validators.required),
      prjName: new FormControl('', [Validators.required, Validators.pattern('^[A-Za-z0-9\d-]+$')]),
      prjDesc: new FormControl(''),
      gitEmail: new FormControl('', Validators.email),
      gitUN: new FormControl(''),
      interface: new FormControl('', Validators.required)
    });
    if (this.gitUserDetail) {
    this.createProjectForm.controls['gitUN'].setValue(this.gitUserDetail.gitUsername);
    this.createProjectForm.controls['gitEmail'].setValue(this.gitUserDetail.gitEmailId);
    this.createProjectForm.controls['gitUN'].disable();
    this.createProjectForm.controls['gitEmail'].disable();
    }
  }
  onTechStackChange(event) {
   this.teckStack = this.techStacks.filter(techStack => techStack.technology === event.value);
   this.interfaceOptions = this.teckStack[0].interfaceOptions;
   console.log('interfaceOptions', this.teckStack[0].defaultInterface);
   this.defaultInterface = this.teckStack[0].defaultInterface;
   this.createProjectForm.patchValue({
     'interface': [this.defaultInterface.interfaceId]
   });
   if (this.interfaceOptions.length === 1 ) {
    this.createProjectForm.controls['interface'].disable();
   }
  }
  createProject(value: string) {
    this.error = false;
    this.errMsg = '';
    if (value['gitUN'] !== '' && value['gitEmail'] === '') {
      this.createProjectForm.controls['gitEmail'].setValidators(Validators.required);
      this.createProjectForm.controls['gitEmail'].updateValueAndValidity();
    }
    if (value['gitEmail'] !== '' && value['gitUN'] === '') {
      this.createProjectForm.controls['gitUN'].setValidators(Validators.required);
      this.createProjectForm.controls['gitUN'].updateValueAndValidity();
    }
    if (value['gitEmail'] === '' && value['gitUN'] === '') {
      this.createProjectForm.controls['gitEmail'].setValidators([]);
      this.createProjectForm.controls['gitEmail'].updateValueAndValidity();
      this.createProjectForm.controls['gitUN'].setValidators([]);
      this.createProjectForm.controls['gitUN'].updateValueAndValidity();
    }
    if (this.createProjectForm.valid) {
      this.projectDetails = {
        'interfaceIds': this.createProjectForm.controls['interface'].value,
        'requesterUserInfoMstrId': this.currentUser.userInfoMstrId,
        'requesterEmailId': this.currentUser.email,
        'requesterUserName': this.currentUser.fullName,
        'projectDescription': this.createProjectForm.value.prjDesc,
        'projectName': this.createProjectForm.value.prjName,
        'techstack': this.createProjectForm.value.techStack
      };

    if (value['gitEmail'] !== '' && value['gitUN'] !== '') {
      this.projectDetails['gitlabCredential'] = {
        'gitLabEmailId':  this.createProjectForm.controls['gitEmail'].value,
        'gitLabUserName':  this.createProjectForm.controls['gitUN'].value
      };
    }
     this.employeeService.createProject(this.projectDetails).subscribe(resp => {
          this.prjResult = resp;
           if (this.prjResult.error == null) {
            this.dialogRef.close();
            this.prjSubmitted.emit({msg : 'Your project request has been submitted successfully.', type: 'success'});
            }
      }, err => {
        this.prjSubmitted.emit({msg : 'Something Went Wrong!', type: 'error'});
      });
    }
  }

  clearError(validation) {
    this.error = false;
    this.errMsg = '';
    this.createProjectForm.reset();
  }
  onCancle() {
     this.dialogRef.close();
  }

}
