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

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

  

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

countries = []; //nationality
identities = []; //الهويه
traineeID: number; //trianer id to edit mode 
traineeForm: NgForm;
typeMode: boolean = false;
hideConfirmPassword: boolean = true; //hide confirm passowrd
checkChangeImage: boolean = false; //check change image profile
typeLink: string = ''; //create or edit word in view 
imageBase64: string = '';
photoType: string = '';
identity_id: number = 0;
identity_type: number;
number_identitiy:number;
checkRequiredSpan:boolean = true;
urlImg: string =  '../../../../assets/image/avatar.png';
checkSaveDisabled:boolean = false;
end:any;
signupForm: FormGroup; //form object group


ngOnInit() {

    //show / hide notification search in header
    this.authSer.notificationLogin = true;
    this.authSer.showSearchHeader = false;
    this.authSer.showHeaderLogin = false;
    this.authSer.showHeaderDashBoard = true;
     //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 profile data
    this.userSer.getUserDataProfile();

   

    

    //get nationality
    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'];
    },
    (error) => {
      console.log(error);
    }
  );



  this.route.params.subscribe(
    (params: Params) => {
      this.traineeID = params['trainnerEditId'];
      if(this.traineeID) {
        this.spineer.show();
        this.typeLink = 'تعديل';
        this.typeMode = true;
        this.hideConfirmPassword = false;
        this.signupForm = new FormGroup({
          name: new FormControl(null, Validators.required),
          type: new FormControl('1'),
          identity_type_id: new FormControl(null, [Validators.required]),
          identity_number: 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)]),
          gender: new FormControl(null, Validators.required),
          birthday: new FormControl(null, Validators.required),
          nationality_id: new FormControl(null, Validators.required),
          phone: new FormControl(null, Validators.required),
          status: new FormControl(null , Validators.required),
        });

        this.dashBoardSer.getItemData(this.traineeID, 'trainee').subscribe(
          (responce) => {
            console.log(responce);      
            this.signupForm.patchValue(
              {
                name: responce['user'].name,
                type: responce['user'].type,
                email: responce['user'].email,
                phone: responce['user'].phone,
                gender: responce['user'].gender,
                birthday: responce['user'].birthday,
                nationality_id: responce['user'].nationality_id,
                status: responce['user'].status,
                identity_type_id: responce['user'].identity_type_id,
                identity_number: responce['user'].identity_number,
              }
            );
            this.urlImg = responce['user'].photo ? this.authSer.pathImg + responce['user'].photo : this.urlImg;
            this.spineer.hide();
          },
          (error) => {
            console.log(error);
          }
        )
      } else {
        this.typeLink = 'إضافه';
        this.signupForm = new FormGroup({
          name: new FormControl(null, Validators.required),
          type: new FormControl('1'),
          identity_type_id: new FormControl(null, [Validators.required]),
          identity_number: 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)]),
          gender: new FormControl(null, Validators.required),
          birthday: new FormControl(null, Validators.required),
          nationality_id: new FormControl(null, Validators.required),
          phone: new FormControl(null, Validators.required),
          status: new FormControl(null , Validators.required),
        });
      }
    }
  )
}









//submitted form
onSubmittedForm() {
  this.checkSaveDisabled = true;
  const userData = this.signupForm.value;  
  if(this.checkChangeImage) {
    userData['photo'] = this.imageBase64;
    userData['photo_type'] = this.photoType[1];
  }

  console.log(userData);
  if(this.typeMode) {
    if(this.signupForm.get('password').value != this.signupForm.get('password_confirmation').value){
      this.toastr.warning('من فضلك تأكد أن كلمه المرور هي نفس تأكيد كلمه المرور ');
      this.checkSaveDisabled = false;
    } else if(this.signupForm.get('identity_number').value.substring(0,1) != 1 && this.signupForm.get('identity_type_id').value == 1){
      this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
      this.checkSaveDisabled = false;
    } else if(this.signupForm.get('identity_number').value.substring(0,1) != 2 && this.signupForm.get('identity_type_id').value == 3){
      this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
      this.checkSaveDisabled = false;
    } else if(this.signupForm.get('phone').value.substring(0,2) != '05') {
      this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
      this.checkSaveDisabled = false;
    } else {
      this.dashBoardSer.editItem(this.traineeID, userData, 'trainee').subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم التعديل بنجاح');
          this.location.back();
          this.checkSaveDisabled = true;
        },
        (error) => {
          console.log(error);
          this.checkSaveDisabled = false;
          if(error.error['error'].email) {
            this.toastr.warning('الايميل تم التسجيل به من قبل !');
          } else if(error.error['error'].identity_number) {
            this.toastr.warning('رقم الهويه تم التسجيل به من قبل !');
          } else {
            this.toastr.error('خطأ في السيرفر سيتم معالجته لاحقاً');
          }
        }
      );
    }
  } else {
    if(this.signupForm.get('password').value != this.signupForm.get('password_confirmation').value){
      this.toastr.warning('من فضلك تأكد أن كلمه المرور هي نفس تأكيد كلمه المرور ');
      this.checkSaveDisabled = false;
    } else if(this.imageBase64 == ''){
      this.toastr.warning('قم بإختيار صوره المستخدم !');
      this.checkSaveDisabled = false;
    } else if(this.signupForm.get('identity_number').value.substring(0,1) != 1 && this.signupForm.get('identity_type_id').value == 1){
      this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
      this.checkSaveDisabled = false;
    } else if(this.signupForm.get('identity_number').value.substring(0,1) != 2 && this.signupForm.get('identity_type_id').value == 3){
      this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
      this.checkSaveDisabled = false;
    } else if(this.signupForm.get('phone').value.substring(0,2) != '05') {
      this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
      this.checkSaveDisabled = false;
    } else {
      this.dashBoardSer.addItem(userData, 'trainee').subscribe(
        (responce) => {
          console.log(responce);
          this.toastr.success('تم الاضافه بنجاح');
          this.location.back();
          this.checkSaveDisabled = true;
        },
        (error) => {
          console.log(error);
          this.checkSaveDisabled = false;
          if(error.error['error'].email) {
            this.toastr.warning('الايميل تم التسجيل به من قبل !');
          } else if(error.error['error'].identity_number) {
            this.toastr.warning('رقم الهويه تم التسجيل به من قبل !');
          }
        }
      );
    }
  }
};

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

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

  //validatiors return funcrtion 
  get password() {
    return this.signupForm.get('password');
  }

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


}
