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

@Component({
  selector: 'app-user-permission',
  templateUrl: './user-permission.component.html',
  styleUrls: ['./user-permission.component.css']
})
export class UserPermissionComponent implements OnInit, OnDestroy {

  subscriptionRouteing: Subscription; //subscription varibale
  permissionSubscription: Subscription; //permissions list subscription
  rolesSubscriptions: Subscription; //roles list subscription
  subscriptionGetUser: Subscription;

  userId: number;
  pages = [];
  pagesId=[];
  roles = [];
  rolesId=[];

  constructor(private authService: AuthServiceService,
      private userSevice: UserService,
      private route: ActivatedRoute,
      private spinner: NgxSpinnerService,
      private toastr: ToastrService,
      private http: HttpClient,
      private location: Location,
      private router: Router) { }

  ngOnInit() {
    this.authService.showDashboardHeader = true;
    this.authService.internalHeader = false;
    

    this.spinner.show();
    //profile data
    this.userSevice.getUserDataProfile();

    this.subscriptionRouteing = this.route.params.subscribe(
      (params:Params) => {
        this.userId = params['userPermissionId'];    
      }
    );

    // //get Permission list
    // this.permissionSubscription = this.userSevice.getPermissionList().subscribe(
    //   (responce) => {
    //     //console.log(responce);
    //     this.pages = responce['pages'];
        
    //     this.spinner.hide();
    //   },
    //   (error) => {
    //     console.log(error);
    //   }
    // );

    //get roles permission list
    this.rolesSubscriptions = this.userSevice.getRolesList().subscribe(
      (responce) => {
        //console.log(responce);
        this.roles = responce['roles'];
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
      }
    );

    //get user data 
    this.subscriptionGetUser = this.userSevice.onGetUserData(this.userId, 'editUs').subscribe(
      (responce) => {
        console.log(responce);
        // for(let i = 0; i < responce['permissions'].length; i++) {
        //   this.pagesId[i] = responce['permissions'][i].id;
        // }

        for(let i = 0; i < responce['roles'].length; i++) {
          this.rolesId[i] = responce['roles'][i].id;
        }


        console.log('edite permissoion id', this.pagesId);
        
        // for(let i = 0; i < this.pagesId.length; i++) {
        //   console.log('paaaaggggesIIIDD', this.pagesId[i]);
        //   for(let j = 0; j < this.pages.length; j++){
        //     console.log('paaaaaaageees', this.pages[j]);
        //     for(let k = 0 ; k < this.pages[j].permissions.length ; k++) {
        //       console.log('permisssions', this.pages[j].permissions[k]);
        //       if(this.pages[j].permissions[k].id == this.pagesId[i]) {
        //         this.pages[j].permissions[k].selected = true;
        //       }
        //     }
        //   }
        // }

        for(let i = 0; i < this.rolesId.length; i++) {
          for(let j = 0; j < this.roles.length; j++){
            if(this.roles[j].id == this.rolesId[i]) {
              this.roles[j].selected = true;
            }
          }
        }
        
      },
      (error) => {
        console.log(error);
      }
    );
  }

  //send post request
  onSubmitted() {
 
    this.rolesId = [];
    //this.pagesId = [];
    const data = {};
    
    // 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) {
    //       this.pagesId.push(this.pages[i].permissions[j].id);
    //     }
    //   } 
    // };


    for(let k = 0; k < this.roles.length; k++) {
      if(this.roles[k].selected == true){
        this.rolesId.push(this.roles[k].id);
      }
    }

    data['roles_id'] = this.rolesId;
    //data['permissions_id'] = this.pagesId;
    data['user_id'] = this.userId;
    console.log(data);

    if(this.roles.length > 0) {
      this.http.post(this.authService.pathApi + '/asign_roles_permissions_to_user', data).subscribe(
        (responce) => {
          this.toastr.success('تم الحفظ');
          console.log(responce);
          this.location.back();
        }
      );
    } else {
      this.toastr.error('please select at least one role');
      this.toastr.error('خطأ التعديل !');
    }
  };


  //when destroy component
  ngOnDestroy(){
    this.subscriptionRouteing.unsubscribe();
    this.rolesSubscriptions.unsubscribe();
    this.subscriptionGetUser.unsubscribe();
  }



}
