import { Component, OnInit } from '@angular/core';
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 { ToastrService } from 'ngx-toastr';
import { Location } from '@angular/common';
import { timer, Observable } from 'rxjs';
import { take, map } from 'rxjs/operators';

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

export class FollowCommunicationsAddComponent implements OnInit {

  pageId: number;
  bindingDateSplitEnd;

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

  parentCategoriesList = [];
  childsCategoriesList: any = [];
  adminstrationsIds: any = [];
  adminstrations: any = [];
  selectedAdminstrations: any = [];


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

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

  communicationData = {
    communication_id: null,
    parent_category_id: null,
    child_category_id: null,
    time_period_id: '',
    maintenance_notes: '',
    status: null,
    closed_status_reason: '',
    urgent_communication: '',
  };

  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;

    //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['followCommunicationId'];
        this.communicationData.communication_id = this.pageId;
        this.reOpenReasonObject.communication_id = this.pageId;
      }
    );

     //get adminstration list 
     this.getAdminstrationList('');

     //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 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);
      }
    );

    //get maintanence data by id
    this.dashBoardSer.getItemData(this.pageId, 'maintenance').subscribe(
      (responce) => {
        
        this.maintData = responce['communication'];
        console.log('main data ', this.maintData);
        this.communicationData.maintenance_notes = this.maintData.maintenance_notes;
        this.communicationData.status = this.maintData.status == 'closed' ? this.maintData.status : false;
        this.communicationData.time_period_id = this.maintData.time_period_id;
        this.communicationData.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;
        
        //get main_location_id
        this.mainLocationVal = this.maintData.main_location_id;
        this.getSublocationList(this.mainLocationVal);
        this.subLocationVal = this.maintData.sub_location_id;

        this.returnEditData(); 
        
        //check status closed or no
        if(this.maintData.reopen == 1) {
          this.checkStatusClosed = true;
        } else {
          this.checkStatusClosed = false;
        }

        this.selectedAdminstrations = [];
        if(this.maintData.adminstrations.length > 0) {
          for(let i = 0; i < this.maintData.adminstrations.length; i++) {
            this.selectedAdminstrations.push(this.maintData.adminstrations[i]);
            for(let j = 0; j < this.adminstrations.length; j++) {
              if(this.maintData.adminstrations[i].id == this.adminstrations[j].id) {
                this.adminstrations[i].selected = true;
              }
            }
          }
        }

        console.log('selected adminstrations', this.selectedAdminstrations);

        
        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'];
        this.spinner.hide();
        console.log('gggg', this.maintData);
        if(this.maintData['files'].length > 0) {
          this.showAttachements = true;
        } else {
          this.showAttachements = false;
        }
        console.log('user data ', this.userData);
      },
      (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);
      }
    );

  

  }

  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);
      }
    );
  };

  //get adminstration list 
  getAdminstrationList(dataSearch) {
    const searchKey = dataSearch ? dataSearch : '';

     this.http.get(this.authSer.pathApi + '/page_list/3/1/1000/all'  + searchKey).subscribe(
      (responce) => {
        console.log('adminstraitions', responce);
        this.adminstrations = responce['adminstrations'];
      },
      (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)
       }
      );
   }
 
   
   changeSubLocation(event){
     console.log(event.target.value);
     this.subLocationVal = event.target.value;
   }

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


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

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

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

  //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)
      }
     );
  }

  //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 remove selected adminsration 
  removeSelectedAdminsration(adminstrationData) {
    console.log(adminstrationData);

    //to remove checked from adminstrations list
      for(let j = 0; j < this.adminstrations.length; j++) {
        if(adminstrationData.id == this.adminstrations[j].id) {
          this.adminstrations[j].selected = false;
        }
      }
    
    const index = this.selectedAdminstrations.indexOf(adminstrationData);
    this.selectedAdminstrations.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);
  }
}


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


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

    if(this.communicationData.urgent_communication) {
      this.communicationData.urgent_communication = '1';
    } else {
      this.communicationData.urgent_communication = '';
    }

    this.communicationData['adminstrations_ids'] = this.adminstrationsIds;
    console.log(this.communicationData);

    if(this.adminstrationsIds.length == 0 && this.communicationData.urgent_communication == '1') {
      this.toastr.warning('قم بإختيار الإدارات');
      this.checkSaveClick = false;
    } else {
      this.http.post(this.authSer.pathApi + '/maintenance_handle_communication', this.communicationData).subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم الحفظ بنجاح');
          this.location.back();
        },
        (error) => {
          console.log(error);
          this.toastr.error('خطأ في الحفظ حاول لاحقاً');
        }
      );
    }

  }

}
