Statistical mechanics of gravity and the thermodynamical origin of time