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-final-accerditation-add',
  templateUrl: './final-accerditation-add.component.html',
  styleUrls: ['./final-accerditation-add.component.css']
})
export class FinalAccerditationAddComponent 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 
  reportId: number;
  stoppedShow: boolean = false;
  endedShow: boolean = false;
  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: '',
    status: '',
    organization_affiliated_with: '',
    department1: '',
    department2: '',
    department3: '',
  }

  //user data object

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

  actionForm = {
   status: '',
   adminstration_notes: '',
   card_received: 0,
   id: null,
  }

  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() {
     //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;
 
     //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['finalAccerditationEdit'];
       }
     );

     if(this.reportId) {

      this.actionForm.id = this.reportId;
      this.disabledInput = true;
      this.spinner.show();
      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.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;

             //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.formData.department1 = responce['data']['request'].departments[0].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
                } else if(i == 1) {
                  this.formData.department2 = responce['data']['request'].departments[i].department_id;
                  this.departmentsId[i] = responce['data']['request'].departments[i].department_id;
                } else if(i == 2) {
                  this.formData.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.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,
              })
            }
          } else {
            console.log('no attachements user add !');
          }
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
        }
      );
    }
 
  }

  recieveCard() {
    this.toastr.success('تم نسجيل الإستلام');
    this.actionForm.card_received = 1
  }

  onSubmittedForm() {
    console.log(this.actionForm);
    this.http.post(this.authSer.pathApi + '/final_accreditation_of_trainees', this.actionForm).subscribe(
      (responce) => {
        console.log(responce),
        this.toastr.success('تم بنجاح');
        this.location.back();
      },
      (error) => {
        console.log(error);
        this.toastr.error('يوجد خطأ في السيرفر ، حاول لاحقاَ');
        this.location.back();
      }
    )
  }

}
