import {Injectable} from '@angular/core';
import {AppUtility} from './app.utility';
import {AppConstants} from './app.constants';

var _ = require('lodash');
var fs = require('fs');
var $refParser = require('json-schema-deref');

@Injectable()

/*
* Service for managing the metadata editor schema
*************************************************************/
export class MetadataEditorService {
  public schema : any;

  constructor() {
    this.schema = this.getUISchema();
  }

  /*
  * Returns the temepalte schema
  ***************************************************************/
  public getUISchema() {
    return {}
  }

  /*
  * Method for retrieve the selected template schema
  ***************************************************************/
  getTemplateSchema(templateType : string, afterSchemaGenerated : (result : Object) => any) : any {
    let path: string = this.getTemplatePathByType(templateType);
    var jsonString = fs.readFileSync(path, 'utf8');
    var schema = JSON.parse(jsonString);

    $refParser(schema, { baseFolder: AppConstants.templateMappingPaths.base_folder }, function(err: any, fullSchema: any) {
      if(err){
        afterSchemaGenerated({result: 'error', messages: err})
      }else{
        afterSchemaGenerated({result: 'ok', schema: fullSchema});
      }
    }); 
  }

  /*
  * Returns the default template type path based on the template  type
  ********************************************************************/
  getTemplatePathByType(templateType : string) : string {
    let path: string;

    switch (templateType) {
        //Default DDI template schema
      case AppConstants.templateTypes.ddi:
        path = AppConstants.templateMappingPaths.default_template_ddi_schema;
        break;

        //Default geospatial template schema
      case AppConstants.templateTypes.geospatial:
        path = AppConstants.templateMappingPaths.default_template_geospatial_schema;
        break;

        //Tree view editor mapping schema
      case AppConstants.templateTypes.editor_mapping:
        path = AppConstants.templateMappingPaths.editor_section_mapping_schema;
        break;
    }

    return path;
  }

}