import { PgUserFileMapping } from 'app/models/employee.model';
import { Location } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { EmployeeNavBarService } from '../employee-nav-bar.service';
import { ActivatedRoute, Router } from '@angular/router';
import { InnovationHttpService } from 'app/services/innovation/innovation-http.service';
import {
  Idea, InnovationStatusObject, getStatusObject, InnovationStatusInfo, InnovationStatus,
  InnovationPOCPayload, InnovationType, POCStatus, ReviewerDetails, File
} from 'app/models/InnovationIdea.model';
import { EmployeeHttpService } from 'app/services/employee/employee-http.service';
import { LocalStorageModule, LocalStorageService } from 'angular-2-local-storage';
import { SafeUrl, DomSanitizer } from '@angular/platform-browser';
import { UserInfo } from 'app/models/userInfo.model';
import { ToastsManager } from 'ng2-toastr/ng2-toastr';
import { environment } from '../../../../environments/environment.dev'
@Component({
  selector: 'app-my-innovation-idea',
  templateUrl: './my-innovation-idea.component.html',
  styleUrls: ['./my-innovation-idea.component.scss']
})

export class MyInnovationIdeaComponent implements OnInit {
  userInfo: UserInfo;
  displayFooter: 'poc' | 'reviewer';
  showAddButton = false;

  private innovationId: number;
  public innovationIdeaDetails: Idea;
  public innovationPOC: InnovationPOCPayload;
  public innovationIdeaStatus: InnovationStatusInfo;
  public employeeDetails: any;
  public coInnovators: any;
  files = { idea: File = undefined, poc: File = undefined};
  reviewerDetails: ReviewerDetails;
  enumInnovationType = InnovationType;
  enumInnovationStatus = InnovationStatus;
  enumPOCStatus = POCStatus;
  imageUrl: string = environment.imageUrl;

  feedbackComments = []

  constructor(
    private innovationHttpService: InnovationHttpService,
    private employeeHttpService: EmployeeHttpService,
    private employeeNavBarService: EmployeeNavBarService,
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private location: Location,
    private localStorage: LocalStorageService,
    private sanitizer: DomSanitizer,
    private toast: ToastsManager
  ) { }

  ngOnInit() {
    this.employeeNavBarService.setCurrentPage(3);
    this.activatedRoute.params.subscribe(params => {
      if (params['id'] !== undefined) {
        this.innovationId = params['id'];
      }
    });


    this.innovationHttpService.getInnovationDetails(this.innovationId).subscribe(response => {
      this.innovationIdeaDetails = response.ideasList[0];
      // Get innovation coinnovators
      const innovators = this.innovationIdeaDetails.coInnovators.map(innovator => {
        return innovator.id;
      });
      // Add innovation creator
      innovators.push(this.innovationIdeaDetails.creator.id);
      // If the current user is a reviewer
      if ([InnovationStatus.InProgress, POCStatus.InProgress].includes(this.innovationIdeaDetails.status) &&
        this.innovationIdeaDetails.reviewer.id === this.userInfo.userInfoMstrId) {
          this.displayFooter = 'reviewer';
          this.reviewerDetails = {
            creatorId: this.innovationIdeaDetails.creator.id,
            reviewerId: this.userInfo.userInfoMstrId,
            innovationId: this.innovationIdeaDetails.innovationId
          };
      } else if (innovators.includes(this.userInfo.userInfoMstrId)) {
        if (this.innovationIdeaDetails.status === InnovationStatus.TakeOff) {
          this.showAddButton = true;
        } else if (this.innovationIdeaDetails.status === POCStatus.Created || this.innovationIdeaDetails.status === POCStatus.Rework) {
          this.displayFooter = 'poc';
        }
      }
      this.innovationIdeaStatus = getStatusObject( this.innovationIdeaDetails.status );
      console.log(this.innovationIdeaStatus);
    });

    this.innovationHttpService.getInnovationFeedbackDetails(this.innovationId).subscribe(response => {

      console.log(response, "getInnovationFeedbackDetails");

      this.feedbackComments = response

    });

    this.userInfo = this.localStorage.get<UserInfo>('userInfo');
  }

  goBack(nav) {
    if (nav) {
      this.router.navigate(['/employee/dashboard']);
    }
  }

  editInnovationIdea() {
    this.router.navigate(['employee/first-time-wizard/innovation/idea/' + this.innovationId]);
  }

  closeInnovationIdea() {
    this.innovationHttpService.updateInnovationIdea({
      submitterId: this.userInfo.userInfoMstrId,
      userInfoMstrId: this.innovationIdeaDetails.creator.id,
      innovationId: this.innovationIdeaDetails.innovationId,
      status: this.innovationIdeaDetails.status === InnovationStatus.Created ? InnovationStatus.Closed : POCStatus.Closed
    }).subscribe((d) => {
      this.toast.success('Innovation successfully closed');
      this.router.navigate(['/employee/dashboard/innovation']);
    }, (e) => {
      this.toast.error('Something went wrong, please try again later');
    });
  }

  pocSubmit(idea: Idea) {
    if (idea) {
      this.innovationIdeaDetails = idea;
      this.innovationIdeaStatus = getStatusObject( this.innovationIdeaDetails.status );
      if (this.innovationIdeaDetails.status === POCStatus.InProgress) {
        this.displayFooter = undefined;
      }
    }
  }

  downloadFile(fileId: number, innovationType: string) {
    if (fileId) {
      if (this.files[innovationType]) {
        this.getFile(this.files[innovationType]);
      } else {
        this.employeeHttpService.getEmployeeRelatedFile(fileId).subscribe((data: File[]) => {
          if (data && data.length > 0 ) {
            this.files[innovationType] = data[0];
            this.getFile(data[0]);
          }
        });
      }
    } else {
        this.toast.error('There was an error, please reload the page and try to download the file again.');
    }
  }

  getFile(file: File) {
    if (file) {
      const b64toBlob = (b64Data, contentType= '', sliceSize= 512) => {
        const byteCharacters = atob(b64Data);
        const byteArrays = [];

        for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
          const slice = byteCharacters.slice(offset, offset + sliceSize);
          const byteNumbers = new Array(slice.length);

          for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
          }

          const byteArray = new Uint8Array(byteNumbers);
          byteArrays.push(byteArray);
        }

        const blob = new Blob(byteArrays, {type: contentType});
        return blob;
      };
      const blob = b64toBlob(file.fileContent, file.contentType);
      const link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = file.fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  }

}
