import { date, string } from 'joi';
// var mongoose = require('mongoose');
import { Schema, model, connect } from 'mongoose';
var sha1 = require('sha1');
var md5 = require('md5');
const jwt = require('jsonwebtoken');
require("dotenv").config();

enum Status {
    PENDING = 'PENDING',
    APPROVED = 'APPROVED',
    REJECTED = 'REJECTED'
}

var userSchema = new Schema(
    {
        title: {
            type: String,
        },
        first_name: {
            type: String
        },
        middle_name: {
            type: String,
            trim: true
        },
        last_name: {
            type: String,
            trim: true
        },
        last_digit_phone: {
            type: String,
            trim: true
        },
        dob: {
            type: String,
            default: null
        },
        phone_number: {
            type: Object
        },
        user_role: {
            type: Schema.Types.ObjectId,
            ref: 'Role'
        },
        gender: {
            type: String,
        },
        email: {
            type: String,
            trim: true
        },
        show_email: {
            type: String,

        },
        profile_pic: {
            type: String,

        },
        formatted_address: {
            type: String,

        },
        primary_specialty_name: {
            type: Array,
        },
        json_address: {
            type: String,

        },
        zip_code: {
            type: String,

        },
        state: {
            type: String,

        },
        city: {
            type: String,

        },
        country: {
            type: String,

        },
        address: {
            type: String,

        },
        branch_of_medicines: {
            type: String,

        },
        primary_specialty: [{
            type: Schema.Types.ObjectId,
            ref: 'Category'
        }],
        additional_specialty: {
            type: String,

        },
        qualification: {
            type: String,

        },
        year_of_practice: {
            type: String,

        },
        additional_qualification: {
            type: String,

        },
        spoken_language: [{
            type: Schema.Types.ObjectId,
            ref: 'Language'
        }],
        certificate: {
            type: Array,
            default: []


        },
        clinic_name: {
            type: String,

        },

        clinic_contact: {
            type: Object,

        },
        clinic_open_time: {
            type: String,

        },
        clinic_close_time: {
            type: String,

        },
        buffer_time: {
            type: Number,

        },
        street_address: {
            type: String,

        },
        location: {
            type: {
                type: String,
                enum: ['Point'],
            },
            coordinates: {
                type: [Number],
            }
        },
        otp: {
            type: String
        },
        password: {
            type: String
        },
        salt_key: {
            type: String
        },
        social_security_number: {
            type: String
        },
        is_account_active: {
            type: Boolean,
            default: true
        },
        is_verified: {
            type: Boolean,
            default: false
        },
        spoken_language_name: {
            type: Array,
            default: []
        },
        is_updated: {
            type: Boolean,
            default: false
        },
        is_deleted: {
            type: Boolean,
            default: false
        },
        //after login, is profile completed 
        is_completed: {
            type: Boolean,
            default: false
        },
        clinic_municipality: {
            type: Object
        },
        clinic_department: {
            type: Object
        },
        // is signup before OTP varification
        is_signup: {
            type: Boolean,
            default: false
        },
        //is OTP confirmed on signup
        is_signup_otp_varify: {
            type: Boolean,
            default: false
        },
        // full time or part time
        is_fulltime: {
            type: Boolean,
            default: true
        },
        clinic_timing: {
            type: Array,
            default: []
        },

        device_data: {
            type: Array,
        },
        auth_token: {
            type: Array
        },
        account_verify_token: {
            type: String
        },
        reset_password_token: {
            type: String
        },
        last_login: {
            type: Date,
            default: new Date()
        },
        user_account_status: {
            type: String,
            enum: Status,
            default: Status.PENDING
        },
        hospital_name : 
        {
            type: String,
            trim : true 
        },
        payment_details: {
            upload_picture: {
                type: String
            },
            input_payment_details: {
                type: String
            }
        },
        selected_language:{
            type: String
        },
        street_address2 : 
        {
            type : String , 
            trim : true 
        },
        is_auto_req_accept : 
        { 
            type : Boolean,
            default : false 
        },
        platform_booking_status : 
        {
            type : Boolean,
            default : true
        },
        guardian_id : 
        {
            type : Schema.Types.ObjectId,
            ref : "User"
        },
        hospital_id : 
        {
            type : Schema.Types.ObjectId,
            ref : 'User'
        },
        relationship : 
        {
            type : String
        }
    },
    {
        timestamps: true,
    },
);

userSchema.index({ location: '2dsphere' });

//pre save hook on mongodb
userSchema.pre('save', async function save(next) {
    if (!this.isModified('password')) return next();
    try {
        const salt = await sha1(`${this.email}${new Date()}`)
        const password = await md5(`${this.password}`)
        this.password = await md5(`${password}${salt}`)
        this.salt_key = salt;
        return next();
    } catch (err) {
        return next(err);
    }
});

userSchema.methods.passwordCompare = async function (saltKey, savedPassword, requestedPassword) {


    const password = await md5(`${requestedPassword}`)
    const encryptedPassword = await md5(`${password}${saltKey}`)
    return (encryptedPassword == savedPassword) ? true : false
}

userSchema.methods.generateToken = async function (saltKey) {

    // let token  = await jwt.sign({ foo: 'bar' }, process.env.JSON_SECRET, { algorithm: 'RS256' }, function(err, token) {
    //     console.log(token);
    //   });
    // return token
    return md5(`${saltKey}-${new Date()}`);
}

userSchema.methods.generateResetPasswordToken = async function (saltKey) {


    return md5(`${saltKey}-${new Date()}`);
}

userSchema.methods.encryptPassword = async function (userData, password) {
    const MD5Password = await md5(`${password}`)
    const encryptedPassword = await md5(`${MD5Password}${userData.salt_key}`)
    return encryptedPassword;
}
let User = model('User', userSchema)

//module.exports.User =  mongoose.model('User', userSchema);
module.exports = { User, userSchema }