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

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

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

  typeLink:string = '';
  userId: number;
  checkSaveClick:boolean = false; //to make save button is disabled when click save 
  disabledInput: boolean = false; //to make button dsabled in create mode 
  showEditField: boolean = false; //to show the field in edit mode 
  showRefusedCause: boolean = false; //to show the cause of refused when ststus is refused
  editMode: boolean = false; //true in edit mode 
  reportId: number;
  attachments_ids = []; //for edit mode;

  countries: any[] = [];
  identities: any[] = [];
  trainees:any[] = [];
  departments:any[] = [];
  departmentsId:any[] = [];

  @ViewChild('f') traineeForm: NgForm;

  //all form data 
  formData = {
    trainee: '',
    type: '',
    specialization_name: '',
    specific_specialization: '',
    university: '',
    level: '',
    training_period: '',
    registration_number: '',
    authority_card_number: '',
    functional_number: '',
    contract_type: '',
    organization_affiliated_with: '',
    department1: '',
    department2: '',
    department3: '',
    department4: '',
    status: '',
    status_description: '',
  }

  //user data object

  userData = {
    name: '',
    email: '',
    nationality_id: '',
    identity_number: '',
    identity_type_id: '',
    birthday: '',
    gender: '',
    phone: '',
  }

  identity_id: number = 0; //to determine te number of identity to validation
  identity_type: number;
  typeMode:boolean = false;

  files = [{
    title : '',
    file: '',
    file_type: '',
    nameFile: '',
    id: null,
  }];

  ngOnInit() {
  

    //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 trainee data
    this.http.get(this.authSer.pathApi + '/get_trainees').subscribe(
      (responce) => {
        this.trainees = responce['users'];
        console.log(this.trainees);
      },
      (error) => {
        console.log(error);
      }
    );

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

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

    if(this.reportId) {

      this.spinner.show();
      this.editMode = true;
      this.typeMode = true;
      this.files = [];

      this.dashBoardSer.getItemData(this.reportId,'traineeRequest').subscribe(
        (responce) => {
          console.log('get request by id', responce);
          this.formData.trainee = responce['data']['user'].id;
          this.formData.type = responce['data']['request'].type;
          this.formData.specialization_name = responce['data']['request'].specialization_name;
          this.formData.specific_specialization = responce['data']['request'].specific_specialization;
          this.formData.level = responce['data']['request'].level;
          this.formData.contract_type = responce['data']['request'].contract_type;
          this.formData.university = responce['data']['request'].university;
          this.formData.authority_card_number = responce['data']['request'].authority_card_number;
          this.formData.training_period = responce['data']['request'].training_period;
          this.formData.status = responce['data']['request'].status;
          this.formData.status_description = responce['data']['request'].status_description;
          this.formData.functional_number = responce['data']['request'].functional_number;
          this.formData.organization_affiliated_with = responce['data']['request'].organization_affiliated_with;
          this.formData.registration_number = responce['data']['request'].registration_number;
          this.userData.name = responce['data']['user'].name;
          this.userData.email = responce['data']['user'].email;
          this.userData.identity_number = responce['data']['user'].identity_number;
          this.userData.identity_type_id = responce['data']['user'].identity_type_id;
          this.userData.phone = responce['data']['user'].phone;
          this.userData.birthday = responce['data']['user'].birthday;
          this.userData.gender = responce['data']['user'].gender;
          this.userData.nationality_id = responce['data']['user'].nationality_id;
          this.userId = responce['data']['user'].id;
          this.userData['id'] = this.userId;

             //full departments in edit mode 
          if(responce['data']['request'].departments.length > 0) {
               this.departments = [];
              for(let i = 0; i < responce['data']['request'].departments.length; i++) {
                this.departments[i] = responce['data']['request'].departments[i];
            }
            this.formData.department4 = responce['data']['request'].departments[0].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.spinner.hide();
        },
        (error) => {
          console.log(error);
        }
      );
    }

    

  }


  statusShow(typeStatus: string) {
    console.log(typeStatus);
    if(typeStatus == 'accepted') {
      this.formData.status = typeStatus;
      this.toastr.success('تم تسجيل الحاله مقبول');
      this.showRefusedCause = false;
    } else if(typeStatus == 'refuced') {
      this.formData.status = typeStatus;
      this.showRefusedCause = true;
      this.toastr.error('تم تسجيل الحاله بالرفض');
    } else if(typeStatus == 'asked_for_opinion') {
      this.formData.status = typeStatus;
      this.showRefusedCause = false;
      this.toastr.warning('تم تسجيل الحاله طلب رأي ');
    }
  }

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


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

   //identitiy input change 
   onIdentitiyChange(event) {
    if(event.length >= 10) {
      this.identity_id = 0;
    } else {
      this.identity_id = this.identity_type;
    }
  }

  getSelectedOptionText(event){
    console.log(event.target.value);
    this.identity_id = event.target.value;
    this.identity_type = event.target.value;
  }

  //get trainee data when subitted form
  getTraineeData(event) {
    console.log(event.target.value);
    this.http.get(this.authSer.pathApi + '/get_user/' + event.target.value).subscribe(
      (responce) => {
        console.log('one trainee data ', responce);
        this.typeMode = true;
        this.disabledInput = true;
        this.userData.name = responce['user'].name;
        this.userData.nationality_id = responce['user'].nationality_id;
        this.userData.identity_type_id = responce['user'].identity_type_id;
        this.userData.identity_number = responce['user'].identity_number;
        this.userData.email = responce['user'].email;
        this.userData.birthday = responce['user'].birthday;
        this.userData.phone = responce['user'].phone;
        this.userData.gender = responce['user'].gender;
        this.userId = responce['user'].id;
      },
      (error) => {
        console.log(error);
      }
    )
  }

  //change file 
  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;
         }
       }

       console.log(this.files);
 
     } 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(this.files);
     }
    console.log('files after change ',this.files);
  }

  //change department
  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.departmentsId[i] != null && this.departmentsId[i+1] != null) {
         this.toastr.warning('يوجد أقسام متشابهه ، يجب أن تكون جميه الاقسام مختلفه');
         this.checkSaveClick = true;
         break;
       } else {
         this.checkSaveClick = false;
       }
     }

  }

  
  //change type 
  changeType(event) {
    console.log(event.target.value);
    this.formData.type = event.target.value;
  }


  onSubmittedForm() {
    
    

    if(this.editMode) {

      this.formData['id'] = this.reportId;
      this.formData['choosen_department_id'] = this.formData['department4'];
      //add old file in new array
      const editAttachements = [];
      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];
         }
        }
      }

  
      if(this.formData.trainee == '') {
        this.toastr.warning('من فضلك قم بإختيار متدرب !');
      } else if(this.formData['choosen_department_id'] == '') {
        this.toastr.warning('يجب إختيار قسم واحد من الأقسام المحدده !');
      } else if(this.formData.status == 'pending') {
        this.toastr.warning('من فضلك قم بإختيار حاله الطلب !');
      } else {
        
        //delete file & file type if not change it in old file
        for(let i = 0; i < editAttachements.length; i++) {
          if(editAttachements[i].file_type == '') {
            delete editAttachements[i].file;
            delete editAttachements[i].file_type;
          }
        }

        //delete the extera key file name 
        for(let i = 0; i < editAttachements.length; i++) {
          delete editAttachements[i].nameFile;
        }
        
        
        //remove old file from files object
        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);
            }
          }
        }

        //remove nameFile and id from object
        for(let i = 0; i < this.files.length; i++) {
          delete this.files[i].nameFile;
          delete this.files[i].id;
        }

        delete this.formData['department1'];
        delete this.formData['department2'];
        delete this.formData['department3'];
        delete this.formData['department4'];


        //add to form the edit old file 
        this.formData['editable_attachments'] = editAttachements;
        this.formData['attachments'] = this.files;
        this.formData['attachments_ids'] = this.attachments_ids;//departments_ids

        const formArraySend = [];
        formArraySend[0] = this.userData;
        formArraySend[1] = this.formData;
        console.log('data send' , formArraySend);

        this.http.post(this.authSer.pathApi + '/edit_request', formArraySend).subscribe(
          (responce) => {
            console.log(responce);
            this.toastr.success('تم التعديل بنجاح');
            this.location.back();
          },
          (error) => {
            console.log(error);
            this.toastr.error('يوجد مشكله في السيرفر يتم العمل عليها حالياً');
          }
        );
      }
    } else {
      //add attachements to json in craete mode
      //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);
        }
      }

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

    

      if(this.departmentsId.length == 0) {
        this.toastr.warning('قم بإختيار قسم كحد أدني !');
      } else if(this.formData.trainee == '') {
        this.toastr.warning('قم بإختيار متدرب !');
      } else {
        //delete extra keies
        delete this.formData.trainee;
        delete this.formData.department1;
        delete this.formData.department2;
        delete this.formData.department3;
        delete this.formData.status;

        for(let i = 0; i < this.files.length; i++) {
          delete this.files[i].nameFile;
          delete this.files[i].id;
        }
        this.formData['attachments'] = this.files; //add files to form json
        this.formData['user_id'] = this.userId;
        console.log(this.formData);
        this.dashBoardSer.addItem(this.formData, 'traineeRequest').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('لا يمكن التعديل طلب جديد ، حتي يتم إجراءات علي الطلب السابق ، شكراً');
                this.location.back();                
              } else {
                this.toastr.error('يوجد مشكله في السرفر ، سيتم معالجتها لاحقاً');
                this.location.back();
                this.location.back();
              }
          }
        );
      }
    }

  }

}
