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

import {EduSchemas} from "../index"

export async function importAllSchemas(){
    try{
      Parse.initialize(global.config['PARSE_APPID'],null,global.config['PARSE_MASTERKEY']);
      Parse.serverURL = global.config['PARSE_SERVERURL'];
      if(global.config["LOCAL"]){
        Parse.serverURL = "http://127.0.0.1:61337/parse"
      }
      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]){
            try{
              await schema.update({useMasterKey:true});
            }catch(err1){}
          }else{
            try{
              await schema.save({useMasterKey:true});
            }catch(err2){}
          }
        // })
      }
    }catch(ierr){
        console.error(ierr)
    }
  
    return
  }
  module.exports.importAllSchemas = importAllSchemas