import { Component, OnInit } from '@angular/core';
import { CategoriesService } from './../../config/category.service';
import { ServiceService } from './../../config/service.service';
import { AuthService } from './../../config/auth.service';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-preference',
  templateUrl: './preference.page.html',
  styleUrls: ['./preference.page.scss']
})
export class PreferencePage implements OnInit {
  type: any;
  successState: boolean;
  uid: any;
  userPrefence: any[];
  loader: boolean;

  constructor(
    private categoriesService: CategoriesService,
    private service: ServiceService,
    private router: Router,
    private authService: AuthService
  ) {
    this.successState = false;
    this.userPrefence = [];
    this.type = 0;
    const users = this.service.get('user').then(data => {
      if (data) {
        data = JSON.parse(data);
        this.uid = data.uid;
        this.categoriesService
          .preference(this.uid)
          .then(datas => {
            // console.log(datas);
            // console.log(this.categoriesService.preferenceList);
            this.userPrefence = this.categoriesService.preferenceList;
            // console.log(this.userPrefence);
          })
          .catch(err => {
            this.userPrefence = [];
          });
      }
    });

    this.service.get('type').then(data => {
      this.type = data;
    });
  }

  ngOnInit() { }

  selectPrefernce(preferenceId) {
    // console.log(this.userPrefence);
    // console.log(preferenceId);
    if (this.userPrefence) {
      const index = this.userPrefence.findIndex(x => x === preferenceId);
      if (index > -1) {
        this.userPrefence.splice(index, 1);
      } else {
        this.userPrefence.push(preferenceId);
      }
    } else {
      this.userPrefence = [];
      this.userPrefence.push(preferenceId);
    }
  }

  onSubmit() {
    this.loader = true;
    // console.log(this.userPrefence);
    this.categoriesService.preferenceCreate(this.userPrefence, this.uid);
    this.successState = true;
    setTimeout(() => {
      this.loader = false;
      this.successState = false;
      this.service.set('type', 0);
      if (this.authService.regState === false) {
        this.authService.regState = true;
        this.router.navigateByUrl('home', { queryParams: null });
      } else {
        this.authService.regState = true;
        this.goBack();
      }
    }, 3000);
  }

  selectedPref(preferenceId) {
    const index = this.userPrefence.findIndex(x => x === preferenceId);
    // console.log(index);
    if (index > -1) {
      return true;
    } else {
      return false;
    }
  }

  goBack() {
    window.history.back();
  }
}