import { Modal } from 'ngx-modialog/plugins/bootstrap';
import { Observable } from 'rxjs/Observable';
import { AuthServiceService } from './../shared/auth-service.service';
import { UserService } from './../shared/user.service';
import { Component, OnInit, Injectable } from '@angular/core';
import { NgForm, FormGroup, FormControl, Validators, FormControlName } from '@angular/forms';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { ToastrService } from 'ngx-toastr';
import { NgxSpinnerService } from 'ngx-spinner';
import {
  NgbDate,NgbDateStruct, NgbCalendar, NgbCalendarIslamicUmalqura, NgbDatepickerI18n
} from '@ng-bootstrap/ng-bootstrap';

const WEEKDAYS = ['ن', 'ث', 'ر', 'خ', 'ج', 'س', 'ح'];
const MONTHS = ['محرم', 'صفر', 'ربيع الأول', 'ربيع الآخر', 'جمادى الأولى', 'جمادى الآخرة', 'رجب', 'شعبان', 'رمضان', 'شوال',
  'ذو القعدة', 'ذو الحجة'];

  @Injectable()
  export class IslamicI18n extends NgbDatepickerI18n {
    getWeekdayShortName(weekday: number) {
      return WEEKDAYS[weekday - 1];
    }

    getMonthShortName(month: number) {
      return MONTHS[month - 1];
    }

    getMonthFullName(month: number) {
      return MONTHS[month - 1];
    }

    getDayAriaLabel(date: NgbDateStruct): string {
      return `${date.day}-${date.month}-${date.year}`;
    }
}

@Component({
  selector: 'app-regester',
  templateUrl: './regester.component.html',
  styleUrls: ['./regester.component.css'],
  providers: [
    {provide: NgbCalendar, useClass: NgbCalendarIslamicUmalqura},
    {provide: NgbDatepickerI18n, useClass: IslamicI18n}
  ]
})



export class RegesterComponent implements OnInit {

  
  constructor(private userService: UserService, 
    private authSer: AuthServiceService, 
    private router: Router, 
    private toastr: ToastrService,
    private spinner: NgxSpinnerService,
    private modal: Modal,
    private route: ActivatedRoute) { }
  
  regesterForm: FormGroup;
  myInnerHeight = window.innerHeight;
  min = '1990-01-31';
  adminstration = [];
  countries = [];
  jobTitils = [];
  specializations = [];
  contracts = [];
  staffs = [];
  departments = [];
  identities = [];
  urlImg: string =  '../../../../assets/image/Group 299.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;
  year: any;
  month:any;
  day:any;
  checkShowSpanRequired: boolean = true;
  changesSave:boolean = false;
  typeMode:boolean = false;
  checkUserType:number;
  showTypeInput:boolean = true; //to show visitor or employee
  typeTitle:string = '';
  bindingDateSplit: any;
  data = {
    name: ''
  }



  ngOnInit() {
    
    this.authSer.showSearchHeader = false;
    this.authSer.notificationLogin = false;
    this.authSer.showDashboardHeader = true;
    this.authSer.arabicTemplate = true;
  
    
    
    this.typeTitle = 'تسجيل الدخول';

    this.route.params.subscribe(
      (params:Params) => {
        this.userProfileId = params['idProfile'];
        if(this.userProfileId) {
          this.showTypeInput = false;
        } else {
          this.showTypeInput = true;
        }
      }
    );


      //start regester form with default employee
      this.regesterForm = new FormGroup({
        name: new FormControl(null, Validators.required),
        type: new FormControl('0'),
        identity_type_id: new FormControl(null, [Validators.required]),
        identity_number: new FormControl(null, Validators.required),
        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),
        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'];
      },
      (error) => {
        console.log(error);
      }
    );

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



    //profile edit
    if(this.userProfileId) {

      this.typeTitle = 'صفحتي';
         //show / hide notification search in header
      this.checkShowSpanRequired = false;
      this.authSer.notificationLogin = true;
      this.authSer.showSearchHeader = false;
      this.authSer.showHeaderLogin = false;
      this.authSer.showHeaderDashBoard = true;
      this.authSer.showDashboardHeader = true;
      this.authSer.internalHeader = false;
      
      this.showStatus = false;
      this.typeMode = true;
      this.authSer.notificationLogin = true;
      

      this.spinner.show();
      this.userService.onGetUserData(this.userProfileId, 'editUs').subscribe(

        (responce) => {
          console.log('userDataaaa', responce['user']);

          this.data.name = responce['user'].name;

          if(responce['user'].type == 1) {
            
            //visitor case
            this.regesterForm = 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]),
              phone: new FormControl(null,Validators.required),
              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),
            });

            this.regesterForm.patchValue({
              name: responce['user'].name,
              type: responce['user'].type,
              identity_type_id: responce['user'].identity_type_id,
              identity_number: responce['user'].identity_number,
              email: responce['user'].email,
              gender: responce['user'].gender,
              birthday: responce['user'].birthday,
              nationality_id: responce['user'].nationality_id,  
              phone: responce['user'].phone,         
            });

            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();

          } else if(responce['user'].type == 0){
            //employee case
            this.regesterForm = 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),
              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),
              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),
            });
            const date = responce['user'].date_of_employment_hij.split('-');  
            this.bindingDateSplit = {
              'year': parseInt(date[0]),
              'month': parseInt(date[1]),
              'day': parseInt(date[2])
            };
  
            console.log('vaaaaaaaaal', this.bindingDateSplit);
  
            this.regesterForm.patchValue({
              name: responce['user'].name,
              type: responce['user'].type,
              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,
              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,
              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,
              date_of_employment_hij: this.bindingDateSplit, //responce['user'].date_of_employment_hij//
            });
            console.log(this.bindingDateSplit);

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


     


      checkTypeUser(typeUser) {
        console.log(typeUser.target.value);
        this.checkUserType = typeUser.target.value;
        if(typeUser.target.value == 1) {
          this.regesterForm = 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),
          });
        } else {
          this.regesterForm = new FormGroup({
            name: new FormControl(null, Validators.required),
            type: new FormControl('0'),
            identity_type_id: new FormControl(null, [Validators.required]),
            identity_number: new FormControl(null, Validators.required),
            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),
            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),
          });
        } 
      }

   


     

    //submitted form 
    onSubmittedForm() {

      this.changesSave = true;
      const userDataRegester = this.regesterForm.value;
      let joinJobDate;

      if(userDataRegester['type'] == '0') {
        userDataRegester['date_of_employment_hij'] = userDataRegester['date_of_employment_hij'].year  + '-' + userDataRegester['date_of_employment_hij'].month + '-' + userDataRegester['date_of_employment_hij'].day;
        joinJobDate = userDataRegester['date_of_employment_gre'].split('-')[0];
      }

      userDataRegester['identity_number'] = userDataRegester['identity_number'].toString();
      console.log('valueee' , userDataRegester);

      const birthDate = userDataRegester['birthday'].split('-')[0];
    


      if(this.checkChangeImage) {
        userDataRegester['photo'] = this.imageBase64;
        userDataRegester['photo_type'] = this.photoType[1];
      }

      
      console.log(userDataRegester);

      if(this.userProfileId) {
        userDataRegester['id'] = this.userProfileId;
        console.log('dataaaaaaaaaaaa', userDataRegester);
        if(this.checkUserType == 1) {
          //edit profile visitor submited 
          if(this.regesterForm.get('password').value != this.regesterForm.get('password_confirmation').value){
            this.toastr.warning(' من فضلك , تأكد أن كلمه المورو نفس تأكيد كلمه المرور!');
          }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.onEditProfile(userDataRegester).subscribe(
              (responce) => {
                console.log(responce);
                this.toastr.success('تم التعديل بنجاح');
              },
              (error) => {
                console.log(error);
                this.toastr.error('فشل التعديل');
                if(error.error['error'].email) {
                  this.toastr.warning('الايميل تم التسجيل به من قبل !');
                } else if(error.error['error'].identity_number) {
                  this.toastr.warning('رقم الهويه تم التسجيل به من قبل !');
                }
              }
            );
          }
        } else {
          //edit profile employee submited 
          if(this.regesterForm.get('password').value != this.regesterForm.get('password_confirmation').value){
            this.toastr.warning(' من فضلك , تأكد أن كلمه المورو نفس تأكيد كلمه المرور!');
          }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(birthDate > joinJobDate) {
            this.toastr.warning('تارخ الميلاد أكبر من تاريخ التوظيف الميلادي !');
          } else if(this.regesterForm.get('phone').value.substring(0,2) != '05') {
            this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
          } else {
            this.userService.onEditProfile(userDataRegester).subscribe(
              (responce) => {
                console.log(responce);
                this.toastr.success('تم التعديل بنجاح');
              },
              (error) => {
                console.log(error);
                this.toastr.error('فشل التعديل');
                if(error.error['error'].email) {
                  this.toastr.warning('الايميل تم التسجيل به من قبل !');
                } else if(error.error['error'].identity_number) {
                  this.toastr.warning('رقم الهويه تم التسجيل به من قبل !');
                }
              }
            );
          }
        }
         
      } else {

        userDataRegester['photo'] = this.imageBase64;
        userDataRegester['photo_type'] = this.photoType[1];
        
        console.log('dataaaaaaaaaaaa', userDataRegester);
        if(this.checkUserType == 1) {
          //visitor added submited
          if(this.regesterForm.get('password').value != this.regesterForm.get('password_confirmation').value){
            this.toastr.warning('  من فضلك تأكد أن كلمه المرور نفس تأكيد كلمه المرور !');
          } else if(this.imageBase64 == '') {
            this.toastr.warning('قم بإختيار صوره شخصيه !');
          }  else if(this.regesterForm.get('phone').value.substring(0,2) != '05') {
            this.toastr.warning('رقم الجوال يجب أن يبدأ ب 05');
          } else if(userDataRegester['identity_number'].substring(0,1) != 1 && this.regesterForm.get('identity_type_id').value == 1){
            this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
          } else if(userDataRegester['identity_number'].substring(0,1) != 2 && this.regesterForm.get('identity_type_id').value == 3){
            this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
          } 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('رقم الهويه تم التسجيل به من قبل !');
                }
              }
            );
          }
        } else {
          //employee added submited
          if(this.regesterForm.get('password').value != this.regesterForm.get('password_confirmation').value){
            this.toastr.warning('  من فضلك تأكد أن كلمه المرور نفس تأكيد كلمه المرور !');
          } else if(this.imageBase64 == '') {
            this.toastr.warning('قم بإختيار صوره شخصيه !');
          } else if(userDataRegester['identity_number'].substring(0,1) != 1 && this.regesterForm.get('identity_type_id').value == 1){
            this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 1');
          } else if(userDataRegester['identity_number'].substring(0,1) != 2 && this.regesterForm.get('identity_type_id').value == 3){
            this.toastr.warning('رقم الهويه يجب ان يبدأ ب رقم 2');
          } else if(birthDate > joinJobDate) {
            this.toastr.warning('تارخ الميلاد أكبر من تاريخ التوظيف الميلادي !');
          } 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('رقم الهويه تم التسجيل به من قبل !');
                }
              }
            );
          }
        }  
      }      
  }
       
}
