import { Component, OnInit, ViewChild } from '@angular/core';
import { LocalStorage } from '../../core/services/local_storage.service';
import { HyperService } from '../../core/services/http.service';
import { ImageCropperComponent, CropperSettings } from 'ng2-img-cropper';
import { LandingComponent } from '../landing/landing.component';
import { Router } from "@angular/router";
import { INgxMyDpOptions, IMyDateModel } from 'ngx-mydatepicker';
import { DatepickerOptions } from 'ng2-datepicker';
import {NgbModule, ModalDismissReasons} from '@ng-bootstrap/ng-bootstrap';
import * as enLocale from 'date-fns/locale/en';
import * as frLocale from 'date-fns/locale/fr';
import * as moment from 'moment';

declare var $: any;
const now = new Date();
@Component({
    selector: 'app-user-profile',
    templateUrl: './user-profile.component.html',
    styleUrls: ['./user-profile.component.scss']
})
export class UserProfileComponent implements OnInit {
    userData: any;
    profile_data: any = {};
    browser_element: any;
    show_croper: boolean = false;
    croper_image: any = {};
    cropperSettings: any;
    image_croped_cords: string = "";
    calendar_option_to: any = {};
    error: string = '';
    start_date: string = '';
    is_edit: boolean = true;
    doj: any;
    dob: any;
    marriage_date: any;
    message_email: string = ""
    message_dob: string = ""
    message_doj: string = ""
    dear_code: any;

    options: DatepickerOptions = {
        minYear: 1900,
        maxYear: 2030,
        displayFormat: 'DD-MMM-YYYY',
        barTitleFormat: 'MMMM YYYY',
        dayNamesFormat: 'dd',
        firstCalendarDay: 0, // 0 - Sunday, 1 - Monday
        locale: enLocale,
        minDate: new Date("Sun Dec 31 1899 17:58:53 GMT+0530 (India Standard Time)"), // Minimal selectable date
        maxDate: new Date(Date.now()),  // Maximal selectable date
        barTitleIfEmpty: 'Click to select a date',
        
        
    };
    @ViewChild('cropper', undefined) cropper: ImageCropperComponent;
    constructor(private server: HyperService, private router: Router) {
        this.cropperSettings = new CropperSettings();
        var today = new Date()
        console.log(today)
    }

    ngOnInit() {
        this.userData = LocalStorage.getValue('user_data');
        this.dear_code = this.userData.dealer.dealer_code + "-" + this.userData.dealer.dealer_name
        console.log(LocalStorage.getValue('user_data').dob)
        // console.log(moment(LocalStorage.getValue('user_data').dob,'YYYY-MM-DD').format("DD-MM-YYYY"))
        let date =moment(LocalStorage.getValue('user_data').dob,'YYYY-MM-DD').format("DD-MM-YYYY")
        this.dob = (LocalStorage.getValue('user_data').dob == '0000-00-00' ? new Date() : LocalStorage.getValue('user_data').dob)
        this.doj = (LocalStorage.getValue('user_data').doj == '0000-00-00' ? new Date() : LocalStorage.getValue('user_data').doj)
        this.marriage_date = (LocalStorage.getValue('user_data').marriage_date == '0000-00-00' ? new Date() : LocalStorage.getValue('user_data').marriage_date)
       
    }
    open(content) {
        
      }
    
      private getDismissReason(reason: any): string {
        if (reason === ModalDismissReasons.ESC) {
          return 'by pressing ESC';
        } else if (reason === ModalDismissReasons.BACKDROP_CLICK) {
          return 'by clicking on a backdrop';
        } else {
          return  `with: ${reason}`;
        }
      }
    edit() {
        this.is_edit = !this.is_edit;  
        console.log(this.is_edit)

    }

    onDateChanged(event: IMyDateModel): void {
        // date selected
    }

    marriedCheck() {
        if (this.userData.is_married == 1) {
            this.userData.is_married = 0
        } else if (this.userData.is_married == 0) {
            this.userData.is_married = 1
        }
        console.log(this.userData.is_married)
    }

    clearValidateMessages() {
        this.message_email = "";
        this.message_dob = "";
        this.message_doj = "";
    }

    isLoginValidated() {
        let isValid = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(this.userData.emailid); 
        console.log(isValid)
        this.clearValidateMessages();
        if(this.userData.emailid == ''){
            this.message_email =   'Email should not be empty';
        }else if(!isValid){
            this.message_email =   'Email should be valid';
        }else{
            this.message_email = ''
        }
        
        this.message_dob = (this.userData.dob == '') ? 'Select DOB' : '';
        this.message_doj = (this.userData.doj == '') ? 'Select DOJ' : '';
        return (this.message_email == '' && this.message_dob == '' && this.message_doj == '') ? true : false;
    }

    updateUserProfile() {
        this.clearValidateMessages();
        console.log(this.isLoginValidated())
        if (this.isLoginValidated()) {
            console.log(moment(this.dob).format("YYYY-MM-DD"))
            
            if (confirm("Are you sure to update your profile details ?")) {
                let send_data: any = {
                    dob: (this.dob == '' ? '0000-00-00' : moment(this.dob).format("YYYY-MM-DD")),
                    email: this.userData.emailid,
                    is_married: this.userData.is_married,
                    marriage_date: (this.marriage_date == '' ? '0000-00-00' : moment(this.marriage_date).format("YYYY-MM-DD")),
                    doj: (this.doj == '' ? '0000-00-00' : moment(this.doj).format("YYYY-MM-DD")),
                }
                console.log('Send DataImg', send_data);
                if (this.profile_data.profile_image != undefined && this.profile_data.profile_image != null && this.profile_data.profile_image != '') {
                    send_data.file = this.profile_data.profile_image;
                    console.log('Send DataImg', send_data.file);
                }
                this.server.fileUpload("user/profile", send_data, true, (data) => {
                    setTimeout(() => {
                        this.getUserDetails();
                    }, 1000);
                    LocalStorage.setValue('loggedIn', true);
                })
            }
        }
    }

    getUserProfile() {
        this.server.get("user/profile").then((data) => {
            if (data.status == 200 && data.result.response != 'failed' && data.result.data != null) {
                this.userData = data.result.data;
                LocalStorage.setValue('userData', this.userData)
            }
            else if (data.result.status == 401 && data.result.response == 'failed') {
                this.router.navigateByUrl('');
            }
            else {
                alert("Oops something happened!");
            }
        })

    }

    resetProfile() {
        // this.getUserProfile()
        this.router.navigateByUrl('/dashboard');
        // setTimeout(() => {
        //     this.userData = LocalStorage.getValue('user_data'); 
        // }, 70   );
    }

    getUserDetails() {
        console.log('UserProfileCalled')
        this.userData = []
        this.server.get("user/profile")
            .then((data) => {
                if (data.status == 200 && data.result.response == "success") {
                    this.userData = data.result.data
                    LocalStorage.setValue('user_data', this.userData);
                    this.router.navigateByUrl('dashboard');

                } else if (data.result.response == "failed") {

                }

            })
    }

    onFileBrowse() {
        console.log("Profile")
        document.getElementById('file_browser').click();
    }

    onFileBrowserChange(event) {
        this.browser_element = event.target;
        this.profile_data.profile_image = event.target.files[0];
        console.log(event.target.files[0])
        let image: any = new Image();
        let reader = new FileReader();
        let that = this;
        this.show_croper = true;
        reader.onload = (e) => {
            let current_file: any = e.target;
            image.src = current_file.result;
            that.cropper.setImage(image);
        }
        reader.readAsDataURL(this.profile_data.profile_image);

    }


    private onImageCroped(data) {
        this.image_croped_cords = data.left + "|" + data.top + "|" + data.width + "|" + data.height;
    }
}