import { InnovationHttpService } from 'app/services/innovation/innovation-http.service';
import { InnovationStatusObject } from 'app/models/InnovationIdea.model';
import { HttpRequest } from '@angular/common/http';
import { Component, OnInit, Input, OnChanges } from '@angular/core';
import { Observable, Subscription } from 'rxjs/Rx';
import { Idea, InnovationStatus, InnovationType } from 'app/models/InnovationIdea.model';
import { LocalStorageService } from 'angular-2-local-storage';
import { CategoryFilter } from 'app/shared/category-filter-modal/category-filter-modal.component';

@Component({
  selector: 'app-innovation-list',
  templateUrl: './innovation-list.component.html',
  styleUrls: ['./innovation-list.component.css']
})
export class InnovationListComponent implements OnInit, OnChanges {
  @Input() ideaList: Idea[];
  @Input() pocList: Idea[];

  private currentUser: any;

  public catFilters: Array<CategoryFilter> = [{
    id: 1,
    title: 'status',
    filters: [
      { id: 0, name: 'All', selected: true },
      { id: 1, name: InnovationStatusObject.InProgress.label }, // 'In Progress' },
      { id: 2, name: InnovationStatusObject.Created.label }, // 'Created' },
      { id: 3, name: InnovationStatusObject.TakeOff.label }] // 'Taken-Off' }]
  }];

  ideaListView: Idea[];

  enumInnovationType = InnovationType;

  constructor(private innovationHttpService: InnovationHttpService, private localStorageService: LocalStorageService) {}

  ngOnInit() {
    this.currentUser = this.localStorageService.get('userInfo') || {};

    this.innovationHttpService.getInnovationCategories()
      .subscribe(cat => {
        const filters = cat.map<{ id: number, name: string, selected?: boolean }>(c => ({ id: c.categoryId, name: c.category }));
        filters.unshift({ id: 0, name: 'All', selected: true });
        const catFil = {
          id: 2,
          title: 'category',
          filters: filters
        };
        this.catFilters.push(catFil);
      });
  }

  ngOnChanges() {
    this.ideaListView = Object.assign(this.ideaList);
  }

  selectFilterIdeas(cf: { catId: number, filterId: number }) {
    const filter = this.catFilters
      .find(f => f.id === cf.catId).filters
      .find(ff => ff.id === cf.filterId);

    if (cf.catId === 1 && cf.filterId !== 0) {
      let status;
      // Find the status by the status label
      Object.keys(InnovationStatusObject).some(key => {
        if (InnovationStatusObject[key].label === filter.name) {
          status = InnovationStatus[key];
          return true;
        }
      });

      this.ideaListView = this.ideaList.filter(idea => idea.status === status);
    } else if (cf.catId === 2 && cf.filterId !== 0) {
      this.ideaListView = this.ideaList.filter(idea => idea.category.categoryName === filter.name);
    } else {
      this.ideaListView = Object.assign(this.ideaList);
    }
  }
}
