#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 13 14:42:52 2023

@author: dj
"""

import pymongo
import json
from bson import json_util
from pymatgen.core.structure import Structure
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer

client=pymongo.MongoClient("mongodb://localhost:27017")
db=client['layers']
col=db['stacking_ionic']
query={'flag':'keep',"$or":[{'phonon.stability':'high'},{'phonon.stability':'stable'}]}

querys=col.find(query)

datas=[]
for data in querys:
    if data['vdw']:
        s=Structure.from_dict(data['structure_vdw_opp'])
        s=SpacegroupAnalyzer(s).get_conventional_standard_structure()
    else:
        s=Structure.from_dict(data['structure_opp'])
        s=SpacegroupAnalyzer(s).get_conventional_standard_structure()
    data['lattice']['a']=s.lattice.a
    data['lattice']['b']=s.lattice.b
    data['lattice']['c']=s.lattice.c
    data['lattice']['alpha']=s.lattice.alpha
    data['lattice']['beta']=s.lattice.beta
    data['lattice']['gamma']=s.lattice.gamma
    entry={'ads_id':data['ads_id'],\
           'band':data['band_opp'],\
           'crys_sys':data['crys_sys'],\
           'e_above_hull':data['e_above_hull'],\
           'efermi':data['efermi_opp'],\
           'etot':data['etot_opp'],\
           'elements':data['elements'],\
           'lattice':data['lattice'],\
           'phonon':data['phonon'],\
           'point_group':data['point_group'],\
           'prototype':data['prototype'],\
           'structure_id':data['structure_id'],\
           'sub_id':data['sub_id'],\
           'vdw':data['vdw'],\
           'spg':data['symmetry']['spg_sym'],\
           'structure':s.as_dict() }
    del entry['band']['path']
    datas.append(entry)

for data in datas:
    structure_id=data['structure_id']
    fileObject=open('./json/'+structure_id+'.json','w')
    fileObject.write(json_util.dumps(data))
    fileObject.close()