Ab initio study of MgH2 formation