import { NgxSpinnerService } from 'ngx-spinner';
import { DashboardService } from './../../shared/dashboard.service';
import { HttpClient } from '@angular/common/http';
import { AuthServiceService } from './../../shared/auth-service.service';
import { ActivatedRoute, Params } from '@angular/router';
import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { Location } from '@angular/common';

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

  constructor(private route: ActivatedRoute, 
    private http: HttpClient,
    private toastr: ToastrService,
    private dashBoardSer: DashboardService,
    private spiner: NgxSpinnerService,
    private location: Location,
    private authService: AuthServiceService) { }

  visitorId: number;
  departments = [];
  departmentsId = [];
  checkSaveClick: boolean = false;
  editMode:boolean = false;
  requestId: number;
  statusType: string = '';

  @ViewChild('f') addRequestFrom: NgForm;


  dataForm = {
    type: '',
    specialization_name: '',
    specific_specialization: '',
    university: '',
    level: '',
    training_period: '',
    registration_number: '',
    authority_card_number: '',
    functional_number: '',
    contract_type: '',
    organization_affiliated_with: '',
    department1: '',
    department2: '',
    department3: '',
  };
  
  files = [{
    title : '',
    file: '',
    file_type: '',
    nameFile: '',
    id: null,
  }];



  attachments_ids = []; //for edit mode;
  departmentsIds = []; //attachemnts id edit
  disabledInput:boolean = false; //disabled button of row in edit mode 
  editButtonShow:boolean = false; //show edit button in edit mode 
  saveButtonShow:boolean = false; //show save button in edit mode 

  ngOnInit() {

    this.authService.checkExternalFooter = false;
    this.authService.arabicTemplate = true; //to make footer is arabic all time
    //show / hide notification search in header
    this.authService.notificationLogin = true;
    this.authService.showSearchHeader = false;
    this.authService.showHeaderLogin = false;
    this.authService.showHeaderDashBoard = true;
    this.authService.showDashboardHeader = true;
    this.authService.internalHeader = false;


    this.route.params.subscribe(
      (params: Params) => {
        this.visitorId = +params['visitorId'];
      }
    );

    //get id of request in edit mode
    this.route.params.subscribe(
    (params: Params) => {
      this.requestId = params['requestId'];
      if(this.requestId) {
        this.statusType = localStorage.getItem('requestStatus');

        this.spiner.show();
        this.files = [];
        this.editButtonShow = true;
        this.disabledInput = true;
        this.editMode = true;
        this.http.get(this.authService.pathApi + '/get_request/' + this.requestId).subscribe(
          (responce) => {
            console.log(responce);
            this.dataForm.type = responce['data']['request'].type;
            this.dataForm.specialization_name = responce['data']['request'].specialization_name;
            this.dataForm.specific_specialization = responce['data']['request'].specific_specialization;
            this.dataForm.university = responce['data']['request'].university;
            this.dataForm.level = responce['data']['request'].level;
            this.dataForm.registration_number = responce['data']['request'].registration_number ? responce['data']['request'].registration_number : '';
            this.dataForm.contract_type = responce['data']['request'].contract_type ? responce['data']['request'].contract_type : '';
            this.dataForm.functional_number = responce['data']['request'].functional_number ? responce['data']['request'].functional_number : '';
            this.dataForm.level = responce['data']['request'].level ? responce['data']['request'].level : '';
            this.dataForm.training_period = responce['data']['request'].training_period ? responce['data']['request'].training_period : '';
            this.dataForm.organization_affiliated_with = responce['data']['request'].organization_affiliated_with ? responce['data']['request'].organization_affiliated_with : '';
            this.dataForm.authority_card_number = responce['data']['request'].authority_card_number ? responce['data']['request'].authority_card_number : '';

            //add departmrnts ids 
            if(responce['data']['request'].departments.length > 0) {
              for(let i = 0; i < responce['data']['request'].departments.length; i++) {
                if(i == 0) {
                  this.dataForm.department1 = responce['data']['request'].departments[0].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
                } else if(i == 1) {
                  this.dataForm.department2 = responce['data']['request'].departments[i].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
                } else if(i == 2) {
                  this.dataForm.department3 = responce['data']['request'].departments[i].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
              }
            }
          }

            if(responce['data']['request'].attachments.length > 0) {
              for(let i = 0; i < responce['data']['request'].attachments.length; i++) {
                this.attachments_ids.push(responce['data']['request'].attachments[i].id);
                this.files.push({
                  title: responce['data']['request'].attachments[i].title,
                  file: '',
                  nameFile: responce['data']['request'].attachments[i].file,
                  file_type: '',
                  id: responce['data']['request'].attachments[i].id,
                })
              }
              console.log('attachements ids', this.attachments_ids);
            } else {
              console.log('no attachements user add !');
            }

            this.spiner.hide();
          },
          (error) => {
            console.log(error);
          }
        );
      }
    }
  );

    this.http.get(this.authService.pathApi + '/training_adminstration_departments').subscribe(
      (responce) => {
        this.departments = responce['departments'];
        console.log(this.departments);
      },
      (error) => {
        console.log(error);
      }
    );

  }



 plusImage() {
   this.files.push({
     title: '',
     file: '',
     file_type: '',
     nameFile: '',
     id: null,
   });
   console.log('files after plus ', this.files);
 }

 onFileChanges(event, index:number) {
   console.log(event);
   console.log(index);
    this.files[index].nameFile = event[0].name.substring(0,20) + '....';
    this.files[index].file = event[0].base64;
    this.files[index].file_type = event[0].type.split('/')[1];
    if(this.editMode) {
      //validate in pdf type file in edit mode 
      if(this.files[index].file_type != '') {
        if(this.files[index].file_type != 'pdf') {
          this.toastr.warning('يجب أن تكون صيغه الملف pdf !');
          this.checkSaveClick = true;
        } else {
          this.checkSaveClick = false;
        }
      }

    } else {
      //validate in pdf type file in create mode 
      if(this.files[index].file_type != 'pdf') {
        this.toastr.warning('يجب أن تكون صيفه الملف pdf !');
        this.checkSaveClick = true;
      } else {
        this.checkSaveClick = false;
      }
    }
   console.log('files after change ',this.files);
 }

 

 changeDepartment(event, typeSelect) {
   console.log(event.target.value);
   if(typeSelect == 1) {
    this.departmentsId[0] = event.target.value;
   } else if(typeSelect == 2) {
    this.departmentsId[1] = event.target.value;
   } else if(typeSelect == 3) {
    this.departmentsId[2] = event.target.value;
   }

  
   
    console.log(this.departmentsId);
    for(let i = 0; i < this.departmentsId.length; i++) {
      if(this.departmentsId[i] == this.departmentsId[i+1]) {
        this.toastr.warning('يوجد أقسام متشابهه ، يجب أن تكون جميه الاقسام مختلفه');
        this.checkSaveClick = true;
        break;
      } else {
        this.checkSaveClick = false;
      }
    }
 }

 changeType(event) {
   this.dataForm.type = event.target.value;
   console.log(this.dataForm.type);
 }

 //delete row from table
 onDeleteRow(index:number) {
   this.files.splice(index , 1);
   if(this.attachments_ids.length > 0) {
     this.attachments_ids.splice(index, 1);
   }
   console.log('files after delete ',this.files);
   console.log('attachements ids', this.attachments_ids);
 }



 onSubmitted() {

  this.addRequestFrom.value['departments_ids'] = [];

  for(let i = 0; i < this.departmentsId.length; i++) {
    this.addRequestFrom.value['departments_ids'][i] = this.departmentsId[i];
  }

  const editAttachements = [];

  if(this.editMode) {

   for(let i = 0; i < this.files.length; i++) {
     for(let j = 0; j < this.attachments_ids.length; j++) {
      if(this.files[i].id == this.attachments_ids[j]) {
       editAttachements[i] = this.files[i];
      }
     }
   }

   

  } else {
    //remove fileName from files and remove file is empty 
    for(let i = 0; i < this.files.length; i++) {
      //delete this.files[i].nameFile;
      if(this.files[i].file_type){
      this.files[i].file_type = this.files[i].file_type.toLowerCase();
      }
      if(this.files[i].file == '') {
      //this.files.splice(this.files.indexOf(this.files[i], 1));
      console.log('empty number ' , i);  
      this.files.splice(i , 1);
      }
    }
    console.log('after submitted form ', this.files);
    this.addRequestFrom.value['attachments'] = this.files; //add files to form json
  }


 

    







  

   if(this.requestId) {
     console.log('attachements ids after submitted' , this.attachments_ids);
    
    //edit mode
    if(this.departmentsId.length == 0) {
      this.toastr.warning('من فضلك ، قم بإختيار قسم كحد أدني !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['registration_number'] == '') {
      this.toastr.warning('قم بإختيار رقم التسجيل !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['authority_card_number'] == '') {
      this.toastr.warning('قم بإختيار  رقم البطاقه الهنيه !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['functional_number'] == '') {
      this.toastr.warning('قم بإختيار الرقم الوظيفي!');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['contract_type'] == '') {
      this.toastr.warning('قم بإختيار نوع العقد !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['organization_affiliated_with'] == '') {
      this.toastr.warning('الجهه التابع لها المتدرب !');
    } else {
      //store departments in object save
        delete this.addRequestFrom.value['department1'];
        delete this.addRequestFrom.value['department2'];
        delete this.addRequestFrom.value['department3'];
        //access edit object of edit attachements (delete the increase data if user not hcnage file )
        for(let i = 0; i < editAttachements.length; i++) {
          if(editAttachements[i].file_type == '') {
            delete editAttachements[i].file;
            delete editAttachements[i].file_type;
          }
        }

          for(let i = 0; i < editAttachements.length; i++) {
            delete editAttachements[i].nameFile;
          }
          this.addRequestFrom.value['editable_attachments'] = editAttachements;
          for(let i = 0; i < editAttachements.length; i++) {
            for(let j = 0; j < this.files.length; j++) {
              if(editAttachements[i].id == this.files[j].id) {
                this.files.splice(j , 1);
              }
            }
          }
          this.addRequestFrom.value['editable_attachments'] = editAttachements;
          this.addRequestFrom.value['attachments'] = this.files;
          this.addRequestFrom.value['attachments_ids'] = this.attachments_ids;
          
          console.log('attachements ids', this.attachments_ids);
          console.log('fillllllllllllllllles ', this.files);
          console.log('ediiiiiit fillllllles', editAttachements);
          console.log('ediiiiiiiiiiiiiiiiiiiite filllles ', editAttachements);
          console.log('form value ', this.addRequestFrom.value);
          


          this.dashBoardSer.editItem(this.requestId, this.addRequestFrom.value,'request').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم التعديل بنحاج');
              this.location.back();
            },
            (error) => {
              console.log(error);
              console.log(error.error['error']);
              if(error.error['error'] == 'can not add new request untill old one done') {
                this.toastr.warning('لا يمكن التعديل طلب جديد ، حتي يتم إجراءات علي الطلب السابق ، شكراً');
                
              } else {
                this.toastr.error('يوجد مشكله في السرفر ، سيتم معالجتها لاحقاً');
                this.location.back();
              }
            }
          );
    }
   } else {
     
    this.addRequestFrom.value['user_id'] = this.visitorId;//add id of user in object
    //add mode
    if(this.departmentsId.length == 0) {
      this.toastr.warning('من فضلك ، قم بإختيار قسم كحد أدني !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['registration_number'] == '') {
      this.toastr.warning('قم بإختيار رقم التسجيل !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['authority_card_number'] == '') {
      this.toastr.warning('قم بإختيار  رقم البطاقه الهنيه !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['functional_number'] == '') {
      this.toastr.warning('قم بإختيار الرقم الوظيفي!');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['contract_type'] == '') {
      this.toastr.warning('قم بإختيار نوع العقد !');
    } else if(this.addRequestFrom.value['type'] == 'fellowship' && this.addRequestFrom.value['organization_affiliated_with'] == '') {
      this.toastr.warning('الجهه التابع لها المتدرب !');
    } else {
    
      //store departments in object save
        delete this.addRequestFrom.value['department1'];
        delete this.addRequestFrom.value['department2'];
        delete this.addRequestFrom.value['department3'];
        console.log('successsss save ' , this.addRequestFrom.value);
        this.dashBoardSer.addItem(this.addRequestFrom.value,'request').subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم الإضافه بنحاج');
            this.addRequestFrom.reset();
            this.location.back();
          },
          (error) => {
            console.log(error);
            console.log(error.error['error']);
            if(error.error['error'] == 'can not add new request untill old one done') {
              this.toastr.warning('لا يمكن إضافه طلب جديد ، حتي يتم إجراءات علي الطلب السابق ، شكراً');
            } else {
              this.toastr.error('يوجد مشكله في السرفر ، سيتم معالجتها لاحقاً');
            }
          }
        );
    }
   }

 }

 onKeyPress(event) {
   console.log(event.target.value);
   if(event.target.value < 0) {
     event.target.value = null;
    event.preventDefault();
   }
 }

}
