import { Modal } from 'ngx-modialog/plugins/bootstrap';
import { TabsService } from './../../../shared/tabs.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ToastrService } from 'ngx-toastr';
import { HttpClient } from '@angular/common/http';
import { UserService } from './../../../shared/user.service';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { NgxSpinnerService } from 'ngx-spinner';

@Component({
  selector: 'app-tab-list',
  templateUrl: './tab-list.component.html',
  styleUrls: ['./tab-list.component.css']
})
export class TabListComponent implements OnInit {

  pageId: number;
  tabsList = [];
  tabsListIds = [];
  count: number;
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  userLoginId:number;
  serviceId:number;
  dataTableNumber: number = 5;
  pages = [];

  constructor(private route: ActivatedRoute, 
    private router: Router, 
    private userSer: UserService,
    private http: HttpClient,
    private tabService: TabsService,
    private toastr: ToastrService,
    private spinner: NgxSpinnerService,
    private modal: Modal,
    private authSer: AuthServiceService) { }

  ngOnInit() {

    this.spinner.show();
    //init the values of permision boolean
    this.authSer.showAddBtn = false;
    this.authSer.showDeleteBtn = false;
    this.authSer.showEditBtn = false;
    //show / hide notification search in header
    this.authSer.notificationLogin = true;
    this.authSer.showSearchHeader = false;
    this.authSer.showHeaderLogin = false;
    this.authSer.showHeaderDashBoard = true;
    this.authSer.internalHeader = false;

    this.route.params.subscribe(
      (params: Params) => {
        this.pageId = params['tabPageId'];
      }
    );
        //to show / hide permissions

  this.route.parent.params.subscribe(
    (params:Params) => {
        this.userLoginId = params['userID'];
        this.serviceId = params['serviceID'];
        this.userSer.getPagesPermetiotns(this.userLoginId, this.serviceId).subscribe(
          (responce) => {
            console.log(responce);
            this.pages = responce['pages'];
            for(let i = 0; i< this.pages.length; i++) {
              if(this.pages[i].id == 12) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_tab'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_tab'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_tabs'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no events');
              }
            }
            this.spinner.hide();
          },
          (error) => {console.log(error)}
        );
      }
    );

    //get list data 
    this.tabService.getTabsList(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.tabsList = responce['tabs'];
        for(let i = 0; i<this.tabsList.length ; i++) {
          var date = this.tabsList[i].created_at.split(' ')[0].split('-');
          this.tabsList[i].created_at = this.authSer.writeHijri( new Date(date[0],date[1],date[2]),'ar','system'); 
        }
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );

  }

  //make all checkbox of user checked 
  selectAll() {
    for (var i = 0; i < this.tabsList.length; i++) {
      this.tabsList[i].selected = this.selectedAll;
    }
  };

  checkIfAllSelected() {
    this.selectedAll = this.tabsList.every(function(item:any) {
      return item.selected == true;
    });
  };

    //filtter function
    filtterFunc(data) {
      this.tabsList = [];
      console.log(data.target.value);
      const dataSearch = data.target.value;     
      this.currentPage = 1;
      console.log('search curent page', this.currentPage);
      this.tabService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.tabsList = responce['tabs'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log('filtter count', this.count);
          console.log('filtter perPagePAgenation', this.perPagePagenation);
        },
        (error) => {
          console.log(error)
        }
      );
    };
  
    //change page 
    onPageChange(pagenationNumber) {
      this.spinner.show();
      this.currentPage = pagenationNumber;
      this.tabsList = [];
      //console.log(pagenationNumber);
      //console.log(this.pageId);
      this.tabService.getTabsList(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.tabsList = responce['tabs'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          console.log(this.tabsList);
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    };

    changeRanking(event, id) {
      const data = {
        id: id,
        ranking: event.target.value,
      };
      console.log(data);
      this.http.post(this.authSer.pathApi + '/rank_tab', data).subscribe(
        (responce) => {
          console.log(responce);
          this.tabService.getTabsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
            (responce) => {
              console.log(responce);
              this.count = responce['count'];
              this.perPagePagenation = responce['per_page'];
              this.tabsList = responce['tabs'];
              console.log(this.tabsList);
              this.spinner.hide();
            },
            (error) => {
              console.log(error);
            }
          )
        },
        (error) => {console.log(error)},
      );
    };
  
  //determine the list count from select element 
  onGetValue(event) {
    this.spinner.show();
    this.tabsList = [];
    this.dataTableNumber = event.target.value;
    this.tabService.getTabsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.tabsList = responce['tabs'];
        this.count = responce['count'];
        this.perPagePagenation = responce['per_page'];
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    );
  }

  onDelete() {

    this.tabsListIds = [];
    for(let i = 0; i < this.tabsList.length; i++) {
      if(this.tabsList[i].selected == true) {
        this.tabsListIds.push(this.tabsList[i].id);
      }
    }

    console.log(this.tabsListIds);

    if(this.tabsListIds.length > 0) {
      const dialogRef = this.modal.alert()
      .size('sm')
      .showClose(true)
      .title('تأكيد الحذف')
      .body(`
          <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
          `)
      .open();
  
        dialogRef.result
        .then( result => 
          this.tabService.deleteTab(this.tabsListIds).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الحذف');
              this.spinner.show();
              this.tabsList = [];
               //get list data 
              this.tabService.getTabsList(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
                (responce) => {
                  console.log(responce);
                  this.tabsList = responce['tabs'];
                  for(let i = 0; i<this.tabsList.length ; i++) {
                    var date = this.tabsList[i].created_at.split(' ')[0].split('-');
                    this.tabsList[i].created_at = this.authSer.writeHijri( new Date(date[0],date[1],date[2]),'ar','system'); 
                  }
                  this.count = responce['count'];
                  this.perPagePagenation = responce['per_page'];
                  this.spinner.hide();
                },
                (error) => {
                  console.log(error);
                  this.spinner.hide();
                }
              );
            },
            (error) => {
              console.log(error);
              this.spinner.hide();
              },
            )
        );
    } else {
      this.toastr.warning('لم يتم إختيار أي عنصر للمسح !');
    }
  };

  //add function
  onAdd() {
    console.log('service/' + this.userLoginId + '/' + this.serviceId + '/addTab');
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/addTab']);
  }

  //edit function
   onEdit(editTabID) {
    this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'tab/edit/' + editTabID]);
  };

  
  

}
