const Errors = require('../lib/errors')

module.exports = (sequelize, DataTypes) => {
	let Ban = sequelize.define('Ban', {
		ReadOnlyMode: {
			type: DataTypes.BOOLEAN,
			defaultValue: false,
			validate: {
				isBoolean (val) {
					if(typeof val !== 'boolean') {
						throw new sequelize.ValidationError('ReadOnlyMode must be a boolean')
					}
				}
			}
		},
		ipBanned: {
			type: DataTypes.BOOLEAN,
			defaultValue: false,
			validate: {
				isBoolean (val) {
					if(typeof val !== 'boolean') {
						throw new sequelize.ValidationError('ipBanned must be a boolean')
					}
				}
			}
		},
		DisableLogin: {
			type: DataTypes.BOOLEAN,
			defaultValue: false,
			validate: {
				isBoolean (val) {
					if(typeof val !== 'boolean') {
						throw new sequelize.ValidationError('DisableLogin must be a boolean')
					}
				}
			}
		},
		message: {
			type: DataTypes.TEXT,
			validate: {
				isString (val) {
					if(typeof val !== 'string') {
						throw new sequelize.ValidationError('message must be a string')
					}
				},
				len: {
					args: [0, 1024],
					msg: 'message must be less than 1024 characters'
				}
			}
		}
	})

	Ban.associate = function (models) {
		Ban.belongsTo(models.User)
	}
	Ban.getBanInstance = function (userid) {
		let ban = Ban.findOne({ where: { UserId: userid } })

		return ban
	}
	Ban.isIpBanned = function (ip, username) {
		let { User, Ip } = sequelize.models

		if(username) {
			let user = User.findOne({ where: {
					username
				}})
			if(user && user.admin) return false
		}


		let users = User.findAll({
			include: [{
				model: Ip,
				where: { ip }
			}]
		})
		if(!users.length) return false

		let ban = Ban.findOne({ where: {
				UserId: {
					$in: users.map(u => u.id)
				},
				ipBanned: true
			} })

		if(ban) {
			throw Errors.sequelizeValidation(sequelize.Sequelize, {
				error: ban.message ||
					'This IP has been banned from creating accounts or logging in'
			})
		} else {
			return false
		}
	}
	Ban.ReadOnlyMode = function (username)  {
		let ban = this.getBanInstance(username)

		if(ban && ban.ReadOnlyMode) {
			throw Errors.sequelizeValidation(sequelize.Sequelize, {
				error: 'You have been set into Read Only mode by an Administrator (aka you\'re banned), Reason: "' + ban.message + '" If you feel like this ban is false, visit /banned' || 'You have been set into Read Only mode by an Administrator. If you would like to object to this ban, visit /banned'
			})
		} else {
			return false
		}
	}
	return Ban
}
