const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');

module.exports = function(sequelize, DataTypes) {
  const users = sequelize.define(
    'users',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

firstName: {
        type: DataTypes.TEXT,
      
      

      },

lastName: {
        type: DataTypes.TEXT,
      
      

      },

phoneNumber: {
        type: DataTypes.TEXT,
      
      

      },

email: {
        type: DataTypes.TEXT,
      
      

      },

disabled: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

password: {
        type: DataTypes.TEXT,
      
      

      },

emailVerified: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

emailVerificationToken: {
        type: DataTypes.TEXT,
      
      

      },

emailVerificationTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

passwordResetToken: {
        type: DataTypes.TEXT,
      
      

      },

passwordResetTokenExpiresAt: {
        type: DataTypes.DATE,
      
      

      },

provider: {
        type: DataTypes.TEXT,
      
      

      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  users.associate = (db) => {

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });

    db.users.belongsToMany(db.permissions, {
      as: 'custom_permissions_filter',
      foreignKey: {
        name: 'users_custom_permissionsId',
      },
      constraints: false,
      through: 'usersCustom_permissionsPermissions',
    });


/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity








    db.users.hasMany(db.classrooms, {
      as: 'classrooms_adviser_teacher',
      foreignKey: {
          name: 'adviser_teacherId',
      },
      constraints: false,
    });


    db.users.hasMany(db.classroom_memberships, {
      as: 'classroom_memberships_student',
      foreignKey: {
          name: 'studentId',
      },
      constraints: false,
    });


    db.users.hasMany(db.teaching_assignments, {
      as: 'teaching_assignments_teacher',
      foreignKey: {
          name: 'teacherId',
      },
      constraints: false,
    });

    db.users.hasMany(db.teaching_assignments, {
      as: 'teaching_assignments_assigned_by',
      foreignKey: {
          name: 'assigned_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.homeworks, {
      as: 'homeworks_teacher',
      foreignKey: {
          name: 'teacherId',
      },
      constraints: false,
    });



    db.users.hasMany(db.homework_extensions, {
      as: 'homework_extensions_created_by_user',
      foreignKey: {
          name: 'created_by_userId',
      },
      constraints: false,
    });


    db.users.hasMany(db.homework_submissions, {
      as: 'homework_submissions_student',
      foreignKey: {
          name: 'studentId',
      },
      constraints: false,
    });


    db.users.hasMany(db.submission_grades, {
      as: 'submission_grades_graded_by_teacher',
      foreignKey: {
          name: 'graded_by_teacherId',
      },
      constraints: false,
    });



    db.users.hasMany(db.gradebooks, {
      as: 'gradebooks_owner_teacher',
      foreignKey: {
          name: 'owner_teacherId',
      },
      constraints: false,
    });



    db.users.hasMany(db.gradebook_entries, {
      as: 'gradebook_entries_student',
      foreignKey: {
          name: 'studentId',
      },
      constraints: false,
    });

    db.users.hasMany(db.gradebook_entries, {
      as: 'gradebook_entries_recorded_by',
      foreignKey: {
          name: 'recorded_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.adviser_reports, {
      as: 'adviser_reports_adviser_teacher',
      foreignKey: {
          name: 'adviser_teacherId',
      },
      constraints: false,
    });

    db.users.hasMany(db.adviser_reports, {
      as: 'adviser_reports_submitted_by_teacher',
      foreignKey: {
          name: 'submitted_by_teacherId',
      },
      constraints: false,
    });


    db.users.hasMany(db.announcements, {
      as: 'announcements_posted_by',
      foreignKey: {
          name: 'posted_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.notifications, {
      as: 'notifications_recipient',
      foreignKey: {
          name: 'recipientId',
      },
      constraints: false,
    });

    db.users.hasMany(db.notifications, {
      as: 'notifications_sent_by',
      foreignKey: {
          name: 'sent_byId',
      },
      constraints: false,
    });


    db.users.hasMany(db.account_applications, {
      as: 'account_applications_applicant',
      foreignKey: {
          name: 'applicantId',
      },
      constraints: false,
    });

    db.users.hasMany(db.account_applications, {
      as: 'account_applications_reviewed_by',
      foreignKey: {
          name: 'reviewed_byId',
      },
      constraints: false,
    });



    db.users.hasMany(db.security_events, {
      as: 'security_events_user',
      foreignKey: {
          name: 'userId',
      },
      constraints: false,
    });



    db.users.hasMany(db.feedback_items, {
      as: 'feedback_items_submitted_by',
      foreignKey: {
          name: 'submitted_byId',
      },
      constraints: false,
    });





//end loop



    db.users.belongsTo(db.roles, {
      as: 'app_role',
      foreignKey: {
        name: 'app_roleId',
      },
      constraints: false,
    });

    db.users.belongsTo(db.schools, {
      as: 'schools',
      foreignKey: {
        name: 'schoolsId',
      },
      constraints: false,
    });



    db.users.hasMany(db.file, {
      as: 'avatar',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: db.users.getTableName(),
        belongsToColumn: 'avatar',
      },
    });


    db.users.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.users.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };


    users.beforeCreate((users, options) => {
        users = trimStringFields(users);

    if (users.provider !== providers.LOCAL && Object.values(providers).indexOf(users.provider) > -1) {
        users.emailVerified = true;

        if (!users.password) {
            const password = crypto
                .randomBytes(20)
                .toString('hex');

            const hashedPassword = bcrypt.hashSync(
            password,
            config.bcrypt.saltRounds,
        );

            users.password = hashedPassword
            }
        }
    });

  users.beforeUpdate((users, options) => {
    users = trimStringFields(users);
  });
  

  return users;
};


function trimStringFields(users) {
  users.email = users.email.trim();

  users.firstName = users.firstName
    ? users.firstName.trim()
    : null;

  users.lastName = users.lastName
    ? users.lastName.trim()
    : null;

  return users;
}

