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

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

export class RegesterComponent implements OnInit {

  
  constructor(private userService: UserService, 
    private authSer: AuthServiceService, 
    private router: Router, 
    private toastr: ToastrService,
    private spinner: NgxSpinnerService,
    private route: ActivatedRoute) { }
  
  regesterForm: FormGroup;
  myInnerHeight = window.innerHeight;

  adminstration = [];
  countries = [];
  jobTitils = [];
  specializations = [];
  contracts = [];
  staffs = [];
  departments = [];
  identities = [];
  urlImg: string =  '../../assets/image/avatar.png';
  showDepart: boolean = false;
  showStatus: boolean = false;
  checkChangeImage: boolean = false;
  imageBase64: string = '';
  photoType: string = '';
  userProfileId: number;
  identity_id: number = 0;
  identity_type: number;
  number_identitiy:number;


  ngOnInit() {
    
    this.authSer.showSearchHeader = false;
    this.authSer.notificationLogin = false;
    this.authSer.showDashboardHeader = true;
    

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

 
    this.regesterForm = new FormGroup({
      name: new FormControl(null, Validators.required),
      identity_type_id: new FormControl(null, [Validators.required]),
      identity_number: new FormControl(null, [Validators.required, Validators.minLength(10)]),
      position: new FormControl(null, Validators.required),
      email: new FormControl(null, [Validators.required,Validators.email]),
      password: new FormControl(null, [Validators.required, Validators.minLength(6)]),
      password_confirmation: new FormControl(null, [Validators.required, Validators.minLength(6)]),
      phone: new FormControl(null, [Validators.required, Validators.minLength(10)]),
      gender: new FormControl(null, Validators.required),
      birthday: new FormControl(null, Validators.required),
      adminstration_id: new FormControl(null, Validators.required),
      department_id: new FormControl(null, Validators.required),
      nationality_id: new FormControl(null, Validators.required),
      date_of_employment_gre: new FormControl(null, Validators.required),
      date_of_employment_hij: new FormControl(null, Validators.required),
      job_title_id: new FormControl(null),
      specialization_id: new FormControl(null),
      functional_number: new FormControl(null, Validators.required),
      contract_type_id: new FormControl(null),
      staff_id: new FormControl(null),
    });

    //get adminstration
    this.userService.getAdministration().subscribe(
      (responce) => {
        console.log(responce);
        this.adminstration = responce['adminstrations'];
      },
      (error) => {console.log(error)}
    );

    

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

    //get job titile
    this.userService.getJobTitle().subscribe(
      (responce) => {
        console.log(responce);
        this.jobTitils = responce['job_titles'];
      },
      (error) =>{console.log(error)}
    );

    //get specialization
    this.userService.getSpecialization().subscribe(
      (responce) => {
        console.log(responce);
        this.specializations = responce['specialization'];
      }
    );

    //get contract list
    this.userService.getContract().subscribe(
      (responce) => {
        console.log(responce);
        this.contracts = responce['contract_types'];
      }
    );

    //get staff list
    this.userService.getStaff().subscribe(
      (responce) => {
        console.log(responce);
        this.staffs = responce['staff'];
      }
    );

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

    if(this.userProfileId) {
      
         //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;
      
      console.log(this.authSer.isAuthenticated());
      this.showStatus = true;
      this.authSer.notificationLogin = true;
      this.regesterForm = new FormGroup({
        name: new FormControl(null, Validators.required),
        identity_type_id: new FormControl(null, [Validators.required]),
        identity_number: new FormControl(null, [Validators.required, Validators.minLength(10)]),
        position: new FormControl(null, Validators.required),
        email: new FormControl(null, [Validators.required,Validators.email]),
        password: new FormControl(null, [Validators.minLength(6)]),
        password_confirmation: new FormControl(null, [Validators.minLength(6)]),
        phone: new FormControl(null, [Validators.required, Validators.minLength(8)]),
        gender: new FormControl(null, Validators.required),
        birthday: new FormControl(null, Validators.required),
        adminstration_id: new FormControl(null, Validators.required),
        department_id: new FormControl(null, Validators.required),
        nationality_id: new FormControl(null, Validators.required),
        date_of_employment_gre: new FormControl(null, Validators.required),
        date_of_employment_hij: new FormControl(null, Validators.required),
        job_title_id: new FormControl(null),
        specialization_id: new FormControl(null),
        functional_number: new FormControl(null, Validators.required),
        contract_type_id: new FormControl(null),
        staff_id: new FormControl(null),
        status: new FormControl(null, Validators.required),
      });

      this.spinner.show();
      this.userService.onGetUserData(this.userProfileId, 'editUs').subscribe(
        (responce) => {
          console.log('userDataaaa', responce['user']);
          this.regesterForm.patchValue({
            name: responce['user'].name,
            identity_type_id: responce['user'].identity_type_id,
            identity_number: responce['user'].identity_number,
            email: responce['user'].email,
            position: responce['user'].position,
            phone: responce['user'].phone,
            password : responce['user'].password,
            gender: responce['user'].gender,
            birthday: responce['user'].birthday,
            adminstration_id: responce['user'].adminstration_id,
            department_id: responce['user'].department_id,
            nationality_id: responce['user'].nationality_id,
            date_of_employment_gre: responce['user'].date_of_employment_gre,
            date_of_employment_hij: responce['user'].date_of_employment_hij,
            job_title_id: responce['user'].job_title_id,
            specialization_id: responce['user'].specialization_id,
            contract_type_id: responce['user'].contract_type_id,
            staff_id: responce['user'].staff_id,
            functional_number: responce['user'].functional_number,
            status: responce['user'].status,
          })
          this.getDepartment();
          console.log('image profile' , this.authSer.pathImg + responce['user'].photo);
          this.urlImg = responce['user'].photo ? this.authSer.pathImg + responce['user'].photo : '../../assets/image/avatar.png';
          this.spinner.hide();
        },
        (error) => {
          console.log(error);
        }
      )
    };

  }
    
    
  //get departmants 
  getDepartment() {
    const adminstrationId = this.regesterForm.get('adminstration_id').value;
    console.log(adminstrationId);
    this.userService.getDepartments(adminstrationId).subscribe(
      (responce) => {
        console.log(responce);
        this.departments = responce['departments'];
        this.showDepart = true;
      }
    );
  }

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

 

    //validatiors return funcrtion 
    get password() {
      return this.regesterForm.get('password');
    }
  
    //validatiors return funcrtion 
    get phone() {
      return this.regesterForm.get('phone');
    }
    
    get repeatPassword() {
      return this.regesterForm.get('password_confirmation');
    }

    get identityNumber() {
      return this.regesterForm.get('identity_number');
    }


      onFileChanges(event) {
        console.log(event);
        this.imageBase64 = event[0].base64;
        this.photoType = event[0].type.split('/');
        console.log(this.photoType[1]);
        console.log(this.imageBase64);
        this.checkChangeImage = true;
      }

      getUrl(event) {   
        if (event.target.files && event.target.files[0]) {
        var reader = new FileReader();
        reader.readAsDataURL(event.target.files[0]); // read file as data url
        reader.onload = (event) => { // called once readAsDataURL is completed
          this.urlImg = event.target['result'];
        }
      }
     }

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

    //submitted form 
    onSubmittedForm() {

      console.log(this.regesterForm);
      const userDataRegester = this.regesterForm.value;
      console.log(userDataRegester);
      if(this.checkChangeImage) {
        userDataRegester['photo'] = this.imageBase64;
        userDataRegester['photo_type'] = this.photoType[1];
      }

      if(this.userProfileId) {
        userDataRegester['id'] = this.userProfileId;
        console.log('dataaaaaaaaaaaa', userDataRegester);
        if(this.regesterForm.get('password').value != this.regesterForm.get('password_confirmation').value){
          this.toastr.warning('please, check password and confirm password !');
        } else if(this.regesterForm.get('identity_number').value.substring(0,1) != 1 && this.regesterForm.get('identity_type_id').value == 1){
          this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
        } else if(this.regesterForm.get('identity_number').value.substring(0,1) != 2 && this.regesterForm.get('identity_type_id').value == 3){
          this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
        } else if(this.regesterForm.get('phone').value.substring(0,2) != '05') {
          this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
        } else {
          this.userService.onEditUser(userDataRegester, 'user').subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم التعديل بنجاح');
            },
            (error) => {
              console.log(error);
              this.toastr.error('فشل التعديل');
            }
          );
        } 
      } else {
        userDataRegester['photo'] = this.imageBase64;
        userDataRegester['photo_type'] = this.photoType[1];
        console.log('dataaaaaaaaaaaa', userDataRegester);
        if(this.regesterForm.get('password').value != this.regesterForm.get('password_confirmation').value){
          this.toastr.warning('please, check password and confirm password !');
        } else if(this.regesterForm.get('identity_number').value.substring(0,1) != 1 && this.regesterForm.get('identity_type_id').value == 1){
          this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
        } else if(this.regesterForm.get('identity_number').value.substring(0,1) != 2 && this.regesterForm.get('identity_type_id').value == 3){
          this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
        } else if(this.regesterForm.get('phone').value.substring(0,2) != '05') {
          this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
        } 
        else {
          this.authSer.signUp(userDataRegester).subscribe(
            (responce) => {
              console.log(responce);
              this.toastr.success('تم اضافتك بنجاح ، من فضلك سجل الدخول')
              this.router.navigate(['login']);
            },
            (error) => {
              console.log(error);
              if(error.error['error'].email) {
                this.toastr.warning('الايميل تم التسجيل به من قبل !');
              } else if(error.error['error'].identity_number) {
                this.toastr.warning('رقم الهويه تم التسجيل به من قبل !');
              }
            }
          );
        }
      }
    }    
}
