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

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

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

  pageId: number;
  newsList = [];
  newsListIds = [];
  count: number;
  perPagePagenation: number;
  p: number[] = [];
  currentPage:number = 1;
  filtterStatus = '';
  selectedAll: any;
  userLoginId:number;
  serviceId:number;
  dataTableNumber: number = 5;
  serviceName: string = '';
  pages = [];


  ngOnInit() {

    this.spinner.show();

    //init the values of permision boolean
    this.route.params.subscribe(
      (params: Params) => {
        this.pageId = params['newsPageId'];
      }
    );

    //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.showDashboardHeader = true;
    this.authSer.internalHeader = false;
    
    this.route.params.subscribe(
      (params: Params) => {
        this.pageId = params['newsPageId'];
      }
    );
    
    //to show / hide permissions

  this.route.parent.params.subscribe(
    (params:Params) => {
        this.userLoginId = params['userID'];
        this.serviceId = params['serviceID'];
        if(this.serviceId == 2) {
          this.serviceName = 'خدمه إداره الصفحه الخارجيه';
        } else if(this.serviceId == 6) {
          this.serviceName = 'خدمه إداره المحتوي';
        }

        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 == 13) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_report'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_report'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_reports'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              } else if(this.pages[i].id == 20) {
                for(let j = 0; j < this.pages[i].permissions.length; j++) {
                  if(this.pages[i].permissions[j].name == 'add_report_ex'){
                    this.authSer.showAddBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'edit_report_ex'){
                    this.authSer.showEditBtn = true;
                  }
                  if(this.pages[i].permissions[j].name == 'delete_reports_ex'){
                    this.authSer.showDeleteBtn = true;
                  }
                }
              }else {
                console.log('no events');
              }
            }
          },
          (error) => {console.log(error)}
        );
      }
    );

    //get list data 
    this.dashBoardService.getListData(this.pageId, this.currentPage ,this.dataTableNumber).subscribe(
      (responce) => {
        console.log(responce);
        this.newsList = responce['reports'];  
        for(let i = 0; i<this.newsList.length ; i++) {
          var date = this.newsList[i].created_at.split(' ')[0].split('-');
          this.newsList[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'];
        console.log('evennnnts', this.newsList);
        //this.spinner.hide();
        if(this.newsList.length > 0) {
          this.spinner.hide();
        }
      },
      (error) => {
        console.log(error);
        this.spinner.hide();
      }
    ); 
  }

    //make all checkbox of user checked 
    selectAll() {
      for (var i = 0; i < this.newsList.length; i++) {
        this.newsList[i].selected = this.selectedAll;
      }
    }
  
    checkIfAllSelected() {
      this.selectedAll = this.newsList.every(function(item:any) {
        return item.selected == true;
      });
    }
  
    //filtter function
    filtterFunc(data) {
      this.newsList = [];
      console.log(data.target.value);
      const dataSearch = data.target.value;     
      this.currentPage = 1;
      this.dashBoardService.getDataUSerSearchBar(dataSearch, this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.newsList = responce['reports'];
          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.newsList = [];
        //console.log(pagenationNumber);
        //console.log(this.pageId);
        this.dashBoardService.getListData(this.pageId, pagenationNumber, this.dataTableNumber).subscribe(
          (responce) => {
            console.log(responce);
            this.newsList = responce['reports'];
            this.count = responce['count'];
            this.perPagePagenation = responce['per_page'];
            console.log(this.newsList);
            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_report', data).subscribe(
        (responce) => {
          console.log(responce);
          this.newService.getnewsList(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
            (responce) => {
              console.log(responce);
              this.count = responce['count'];
              this.perPagePagenation = responce['per_page'];
              this.newsList = responce['reports'];
              console.log(this.newsList);
              this.spinner.hide();
            },
            (error) => {
              console.log(error);
            }
          )
        },
        (error) => {console.log(error)},
      );
    };
  
    //determine the list count from select element 
    onGetValue(event) {
      this.spinner.show();
      this.newsList = [];
      this.dataTableNumber = event.target.value;
      this.dashBoardService.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
        (responce) => {
          console.log(responce);
          this.newsList = responce['reports'];
          this.count = responce['count'];
          this.perPagePagenation = responce['per_page'];
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
          this.spinner.hide();
        }
      );
    };
    
    onDelete() {

      for(let i = 0; i < this.newsList.length; i++) {
        if(this.newsList[i].selected == true) {
          this.newsListIds.push(this.newsList[i].id);
        }
      }
  
      console.log(this.newsListIds);

      if(this.newsListIds.length > 0) {
        const dialogRef = this.modal.alert()
        .size('sm')
        .showClose(true)
        .title('تأكيد الحذف')
        .body(`
            <h4>هل ترغب في حذف العناصر المحدده ؟ </h4>
            `)
        .open();
        dialogRef.result
        .then( result =>  
          this.dashBoardService.deleteItem(this.newsListIds, this.pageId).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم الحذف');
              this.spinner.show();
              this.newsList = [];
              this.dashBoardService.getListData(this.pageId, this.currentPage, this.dataTableNumber).subscribe(
                (responce) => {
                  console.log(responce);
                  this.newsList = responce['reports'];
                  this.count = responce['count'];
                  this.perPagePagenation = responce['per_page'];
                  this.spinner.hide();
                },
                (error) => {
                  console.log(error);
                  this.spinner.hide();
                }
              );
            },
            (error) => {
              this.toastr.success('يوجد خطأ إنتظر قليلا وأعد المحاوله ');
              console.log(error);
              this.spinner.hide();
            },
          )
        );
      } else {
        this.toastr.warning('لم يتم إختيار أي عنصر للمسح !');
      }
    };
  
    //add function
    onAdd() {
      console.log('service/' + this.userLoginId + '/' + this.serviceId + '/addNews');
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/addNews']);
    }
  
    //edit function
     onEdit(editNewID) {
      this.router.navigate(['service/' + this.userLoginId + '/' + this.serviceId + '/' + 'new/edit/' + editNewID]);
    }
    
}
