import { HttpClient } from '@angular/common/http';
import { Location } from '@angular/common';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { UserService } from './../../../shared/user.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { NgForm } from '@angular/forms';
import { RolesService } from './../../../shared/roles.service';
import { Component, OnInit, ViewChild, OnDestroy } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-add-roles',
  templateUrl: './add-roles.component.html',
  styleUrls: ['./add-roles.component.css']
})

export class AddRolesComponent implements OnInit, OnDestroy {
  constructor(private rolesService: RolesService,
      private userService: UserService,
      private location: Location,
      private toastr: ToastrService,
      private authSer: AuthServiceService,
      private route: ActivatedRoute, 
      private spineer: NgxSpinnerService) { 
        this.spineer.show();
      }
  
  @ViewChild('f') addRoleData: NgForm;  
  checkModePage: boolean = false;
  selectChange: boolean = false;
  typeLink: string = '';
  roleId: number;
  checkSaveDisabled:boolean = false;

  pages = []; //فيها كل حاجه السيرفيس والصفحات والصلاحيات
  permisionsId = [];
  permissionList = [];
  servicePages = []; //بخزن فيها الصفحات والصلحيات لما يغير السيليكت بوكس
  allPages = []; //بلوب علشان احزن فيها كل الصلاحيات والصفحات كلهم فارا واحده ال17
  getPerId = []; //to stroe all get id permissions

  subscriptionPermisions: Subscription;


  user = {
    roleName: '',
    descriptionRole: '',
    statusRole: '',
  };

  ngOnInit() {
    //show / hide notification search in header
    this.authSer.notificationLogin = true;
    this.authSer.showSearchHeader = false;
    this.authSer.showHeaderLogin = false;
    this.authSer.showHeaderDashBoard = true;
    //show / hide notification search in header
    this.authSer.notificationLogin = true;
    this.authSer.showSearchHeader = false;
    this.authSer.showHeaderLogin = false;
    this.authSer.showHeaderDashBoard = true;
    this.authSer.showDashboardHeader = true;
    this.authSer.internalHeader = false;
    
    this.rolesService.getPermissionList().subscribe(
      (responce) => {
        this.pages = responce['services'];
        for(let i = 0; i < this.pages.length; i++){
          for(let j = 0; j < this.pages[i].pages.length; j++){
            this.allPages.push(this.pages[i].pages[j]);
          }
        }
        console.log('pagesss', this.pages);
        console.log('all pages', this.allPages);

        this.spineer.hide();
      },
      (error) => {
        console.log(error);
      }
    );

    this.userService.getUserDataProfile();//get profile data
   
    
   this.subscriptionPermisions = this.route.params.subscribe(
      (params: Params) => {
        if(params['typeRoleMode'] == 'edit') {
          this.typeLink = 'تعديل';
          this.spineer.show();
          this.checkModePage = true;
          this.roleId = params['roleEditId'];
          //alert(this.checkModePage);
          this.rolesService.getRoleData(this.roleId).subscribe(
            (responce) => {
              console.log('rrrrrr',responce);
              this.user.roleName = responce['role'].role_name;
              this.user.descriptionRole = responce['role'].description;
              this.user.statusRole = responce['role'].status;
              for(let i = 0; i < responce['role'].permissions.length; i++) {
                this.getPerId[i] = responce['role'].permissions[i].permission_id;
              }
              console.log(this.getPerId);
             
              this.spineer.hide();
            },
            (error) => {
              console.log(error);
            }
          )
        } else {
          this.typeLink = 'إنشاء جديد';
          this.spineer.hide();
        }
      }
    );
  }


  onSelectChange(event) {
    //to make the checkboxes in edit is checked
    for(let k = 0; k < this.getPerId.length; k++){
      for(let i = 0 ; i < this.allPages.length; i++) {
        for(let j = 0 ; j < this.allPages[i].permissions.length ; j++) {
          if(this.allPages[i].permissions[j].id == this.getPerId[k]) {
            this.allPages[i].permissions[j].selected = true;
          }
        }
      };
    }
    console.log(event.target.value);
    for(let i = 0; i < this.pages.length; i++) {
      if(this.pages[i].id == event.target.value) {
        this.servicePages = this.pages[i].pages;
        console.log(this.servicePages);
      }
    }
    //this.selectChange = true;
  }

 

  onSubmitted() {

    // for(let i = 0 ; i < this.pages.length; i++) {
    //   for(let j = 0 ; j < this.pages[i].permissions.length ; j++) {
    //     if(this.pages[i].permissions[j].selected == true) {
    //       alert(this.pages[i].permissions[j].name)
    //       this.permisionsId.push(this.pages[i].permissions[j].id);
    //     }
    //   } 
    // };

    this.checkSaveDisabled = true;

    for(let i = 0; i < this.allPages.length; i++) {
      for(let j = 0; j < this.allPages[i].permissions.length; j++) {
        if(this.allPages[i].permissions[j].selected == true) {
          this.permisionsId.push(this.allPages[i].permissions[j].id);
        }
      }
    }

    delete this.addRoleData.value['permissions_id'];
    this.addRoleData.value['permissions_id'] = this.permisionsId;

    console.log(this.addRoleData);

    if(this.checkModePage){      
      this.rolesService.editRole(this.addRoleData.value, this.roleId).subscribe(
        (responce) => {
          this.checkSaveDisabled = false;
          this.toastr.success('تم التعديل');
          this.location.back();
        },
        (error) => {
          this.checkSaveDisabled = false;
          console.log(error);
          this.toastr.error('خطأ التعديل !');
        }
      );
    } else {
      this.rolesService.addRoles(this.addRoleData).subscribe(
        (responce)=>{
          this.checkSaveDisabled = false;
          this.toastr.success('تم الاضافه بنجاح');
          this.location.back();
        },
        (error) => {
          this.checkSaveDisabled = false;
          console.log(error);
          this.toastr.error('خطأ الاضافه !');
        }
      );
    }
  }

  ngOnDestroy() {
    this.subscriptionPermisions.unsubscribe();
  }

}
