import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';
import { NgxSpinnerService } from 'ngx-spinner';
import { UserService } from 'src/app/shared/user.service';
import { DashboardService } from './../../../shared/dashboard.service';
import { AuthServiceService } from './../../../shared/auth-service.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { Location, formatDate } from '@angular/common';
import { timer } from 'rxjs';
import { take, map } from 'rxjs/operators';

@Component({
  selector: 'app-follow-communications-adminstration-edit',
  templateUrl: './follow-communications-adminstration-edit.component.html',
  styleUrls: ['./follow-communications-adminstration-edit.component.css']
})
export class FollowCommunicationsAdminstrationEditComponent implements OnInit {

  pageId: number;
  userAdminstrationId: number;
  bindingDateSplitEnd;

  maintData:any = [];
  userData:any = [];
  times:any = [];
  locationList: any = [];
  subLocationList: any = [];

  parentCategoriesList = [];
  childsCategoriesList: any = [];
  departmentsIds: any = [];
  departments: any = [];
  selectedDepartments: any = [];


  //reopen object 
  reOpenReasonObject = {
    communication_id: null,
    reopen_closed_communication: '',
  }

  selectedAll: any;
  mainLocationVal = '';
  subLocationVal = '';
  checkSaveClick: boolean = false;
  checkStatusClosed: boolean = false;

  communicationData = {
    parent_category_id: null,
    child_category_id: null,
    time_period_id: '',
    maintenance_notes: '',
  };

  formData = {
    communication_id: null,
    closed_status_reason: '',
    adminstration_notes: '',
    status: null,
  }

  countries = [];
  identities = [];

  disabledInput: boolean = true;
  showAttachements: boolean = false;
  disabledVal: boolean = true;
  adminstrationsButtonDisabled: boolean = false;

  counter$: Observable<number>;
  counter = 180;

  constructor(private route: ActivatedRoute, 
    private dashBoardSer: DashboardService,
    private userSer: UserService,
    private http: HttpClient,
    private toastr: ToastrService,
    private location: Location,
    private spinner: NgxSpinnerService,
    public authSer: AuthServiceService) { }

  ngOnInit() {

    this.spinner.show();
      //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.userAdminstrationId = +localStorage.getItem('adminId');
      //reload page every 10 seconds
     
      setTimeout(function(){
        location.reload(); 
      },180000);

  

      this.counter$ = timer(0,1000).pipe(
        take(this.counter),
        map(() => --this.counter)
      );
      
    //get maintenance id
    this.route.params.subscribe(
      (params: Params) => {
        this.pageId = params['followAdminEditId'];
        this.formData.communication_id = this.pageId;
      }
    );

     //get sections list 
     this.getsectionsList('');

     //get nationality data
     this.userSer.getNationality().subscribe(
      (responce) => {
        console.log(responce);
        this.countries = responce['countries'];
      },
      (error) => {
        console.log(error);
      }
    );

    //get identites
    this.userSer.onGetIdentities().subscribe(
      (responce) => {
        this.identities = responce['identities'];
        console.log('idddentiiiesssssssssss', this.identities);
      },
      (error) => {
        console.log(error);
      }
    );


    //get parent_categories_list
    this.http.get(this.authSer.pathApi + '/parent_categories_list').subscribe(
      (responce) => {
        console.log('parent_categories_list', responce);
        this.parentCategoriesList = responce['categories'];
      },
      (error) => {
        console.log(error);
      }
    );

    //get maintanence data by id
    this.dashBoardSer.getItemData(this.pageId, 'maintenance').subscribe(
      (responce) => {
        
        this.maintData = responce['communication'];
        if(this.maintData.reopen == 1) {
          this.checkStatusClosed = true;
        } else {
          this.checkStatusClosed = false;
        }
        console.log('main data ', this.maintData);
        this.communicationData.maintenance_notes = this.maintData.maintenance_notes;
        this.formData.status = this.maintData.status == 'closed' ? this.maintData.status : false;
        this.communicationData.time_period_id = this.maintData.time_period_id;
        this.formData.closed_status_reason = this.maintData.closed_status_reason ? this.maintData.closed_status_reason : '';
        this.communicationData.parent_category_id = this.maintData.parent_category_id;
        this.getChildGategories(this.communicationData.parent_category_id);
        this.communicationData.child_category_id = this.maintData.child_category_id;
        this.formData.adminstration_notes = this.maintData.adminstration_notes;
        //get main_location_id
        this.mainLocationVal = this.maintData.main_location_id;
        this.getSublocationList(this.mainLocationVal);
        this.subLocationVal = this.maintData.sub_location_id;

        this.returnEditData();
        
        this.bindingDateSplitEnd = {
          year: parseInt(this.maintData.created_date.split('-')[0]),
          month: parseInt(this.maintData.created_date.split('-')[1]),
          day: parseInt(this.maintData.created_date.split('-')[2]),
        }

        this.userData = responce['communication']['user'];
        
        console.log('gggg', this.maintData);
        if(this.maintData['files'].length > 0) {
          this.showAttachements = true;
        } else {
          this.showAttachements = false;
        }
        console.log('user data ', this.userData);
        this.spinner.hide();
      },
      (error) => {
        console.log(error);
      }
    );

    //get time period 
    this.http.get(this.authSer.pathApi + '/page_list/53/1/1000/for_communication').subscribe(
      (response) => {
        console.log('time period', response);
        this.times = response['time_periods'];
      },
      (error) => {
        console.log(error);
      }
    );

    //get location parent
    this.http.get(this.authSer.pathApi + '/parent_locations_list').subscribe(
      (response) => {
        this.locationList = response['locations'];
        console.log('parent location' , this.locationList);
      },
      (error) => {
        console.log(error);
      }
    );

  }

  changeParentCategory(event) {
    console.log(event.target.value);
    this.getChildGategories(event.target.value);
  }  


  //get child gategories 
  getChildGategories(parentId: number) {
    this.http.get(this.authSer.pathApi + '/childs_categories_list_by_parent_id/' + parentId).subscribe(
      (responce) => {
        console.log('childs_categories_list_by_parent_id', responce);
        this.childsCategoriesList = responce['categories'];
      },
      (error) => {
        console.log(error);
      }
    );
  };

  onChangemainLocation(event){
    const id = event.target.value
    this.mainLocationVal = id;
     this.http.get(this.authSer.pathApi + '/childs_locations_list_by_parent_id/' + id).subscribe(  
       (response)  => {
         console.log(id);
         this.subLocationList = response['locations'];
         
       },
       (error) => {
         console.log(error)
       }
      );
   }
   
  //get adminstration list 
  getsectionsList(dataSearch) {
    const searchKey = dataSearch ? dataSearch : '';
    console.log('urrrl', this.authSer.pathApi + '/page_list/4/1/1000/' + this.userAdminstrationId);
     this.http.get(this.authSer.pathApi + '/page_list/4/1/1000/' + this.userAdminstrationId  + searchKey).subscribe(
      (responce) => {
        console.log('sections', responce);
        this.departments = responce['departments'];
        console.log('sections', responce);
      },
      (error) => {
        console.log(error);
      }
    );
  };

  //search function 
  filtterFunc(event) {
    this.departments = [];
    console.log(event.target.value);
    this.getsectionsList(event.target.value);
  }


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

  //to checked one checkBox 
  checkIfAllSelected() {
    this.selectedAll = this.departments.every(function(item:any) {
      return item.selected == true;
    });
  }

  //get departments ids 
  getDepartments() {
    this.selectedDepartments = [];
    for(let i = 0; i < this.departments.length; i++) {
      if(this.departments[i].selected == true) {
        this.selectedDepartments.push(this.departments[i]);
      }
    }
    console.log(this.selectedDepartments);
  }

  
 

 

  //get sub location list 
  getSublocationList(parentId: any) {
    this.http.get(this.authSer.pathApi + '/childs_locations_list_by_parent_id/' + parentId).subscribe(  
      (response)  => {
        this.subLocationList = response['locations'];
        console.log('sub Location', this.subLocationList);
      },
      (error) => {
        console.log(error)
      }
     );
  }

  changeSubLocation(event){
    console.log(event.target.value);
    this.subLocationVal = event.target.value;
  }

  //get value of reason reOpen
  getReopenReason(event) {
    console.log(event.target.value);
    console.log(this.reOpenReasonObject);
    this.reOpenReasonObject.reopen_closed_communication = event.target.value;
  }

  //reOpen mentainence function
  reOpenMaintenance() {
    this.http.post(this.authSer.pathApi + '/reopen_closed_communication', this.reOpenReasonObject).subscribe(
      (responce) => {
        console.log(responce);
        this.toastr.success('تم إعاده الفتح بنجاح');
        this.location.back();
      },
      (error) => {
        console.log(error);
        this.toastr.error('حدث خطا في الحفظ ، حاول لاحقاً');
        this.location.back();
      }
    );
  }


  //remove selected adminsration 
  removeSelectedAdminsration(departmentData) {
    console.log(departmentData);

    //to remove checked from adminstrations list
      for(let j = 0; j < this.departments.length; j++) {
        if(departmentData.id == this.departments[j].id) {
          this.departments[j].selected = false;
        }
      }
    
    const index = this.selectedDepartments.indexOf(departmentData);
    this.selectedDepartments.splice(index, 1);
    
    console.log(index);
  }

  //return substring of subject and check negaive and positive time 
    returnEditData() {
      for(let i = 0; i < this.maintData['adminstrations'].length; i++) {
          this.maintData['adminstrations'][i].countdown = this.maintData['adminstrations'][i].countdown ? this.dashBoardSer.secondsToDhms(this.maintData['adminstrations'][i].countdown) : '-';
          console.log(this.maintData['adminstrations'][i].countdown);
      }
    }

    //on print
    onPrint() {
      window.print();
    }

  //submitted form 
  onSubmittedForm() {
    
    //this.checkSaveClick = true; //make save btn disabled till request is success 


    if(this.formData.status) {
      this.formData.status = 'closed';
    } else {
      this.formData.status = '';
      this.formData.closed_status_reason = '';
    }

    this.departmentsIds = [];
    for(let i = 0; i < this.selectedDepartments.length; i++) {
      this.departmentsIds.push(this.selectedDepartments[i].id);
    }

    this.formData['departments_ids'] = this.departmentsIds;

   console.log(this.formData);


   if(this.formData.status == 'closed' && this.formData.closed_status_reason == '') {
     this.toastr.warning('أدخل سبب الرفض !');
   } else {
      this.http.post(this.authSer.pathApi + '/adminstration_handle_communication', this.formData).subscribe(
      (responce) => {
        console.log(responce['status']);
        if(responce['status'] == 'some adminstrations didnt closed yet') {
          this.toastr.warning('بعض الأقسام لم تقم بإغلاق البلاغ بعد !');
        } else {
          this.toastr.success('تم الحفظ بنجاح');
          this.location.back();
        }
      },
      (error) => {
        console.log(error);
        this.toastr.error('خطأ في الحفظ حاول لاحقاً');
      }
    );
   }

  }

}
