const Parse = require("parse/node")
Parse.Cloud.useMasterKey();

const EduSchemas = require("../index").EduSchemas

async function importAllSchemas(){
    try{
      Parse.initialize(global.config['PARSE_APPID'],null,global.config['PARSE_MASTERKEY']);
      Parse.serverURL = global.config['PARSE_SERVERURL'];
      Parse.Cloud.useMasterKey()
      Parse.Cloud.useMasterKey(true)
    //   Parse.masterKey = global.config['PARSE_MASTERKEY'];
      console.log(Parse.applicationId)
      console.log(Parse.serverURL)
      console.log(Parse.masterKey)
      SchemaMap = {}
      let SchemaList = await Parse.Schema.all()
      SchemaList?.forEach(item=>{
        SchemaMap[item?.className] = item
      })
  
      for (let index = 0; index < EduSchemas.length; index++) {
        let schemaJson = EduSchemas[index];
        // EduSchemas.forEach(async schemaJson=>{
          console.log(schemaJson?.className,"schema loaded.")
          let schema = new Parse.Schema(schemaJson?.className);
  
        schemaJson.fields["isDeleted"] = {
          "type": "Boolean",
          "required": false
        }
        schemaJson.fields["company"] = {
            "type": "Pointer",
            "targetClass":"Company",
            "required": false
        }    
          Object.keys(schemaJson?.fields)?.forEach(key=>{
            if(key=="objectId"||key=="ACL"||key=="createdAt"||key=="updatedAt") return
            let field = schemaJson?.fields[key]
            let options = {}
            if(field?.targetClass) options.targetClass = field?.targetClass
            schema.addField(key,field?.type,options)
          })
          let clp = new Parse.CLP();
          clp.setPublicReadAccess(true);
          clp.setPublicWriteAccess(true);
          schema.setCLP(clp);
          if(SchemaMap[schemaJson?.className]){
            await schema.update({useMasterKey:true});
          }else{
            await schema.save({useMasterKey:true});
          }
        // })
      }
    }catch(ierr){
        console.error(ierr)
    }
  
    return
  }
  module.exports.importAllSchemas = importAllSchemas
  