/**
 * @param $form
 * @param $form_state
 * @return mixed
 */
function gd_sync_export_form ( $form, &$form_state ) {

    if ( !empty($form_state['values']['datasource']) ) {

        $exportContext = new GD\Sync\Export\ExportContext(array('datasourceName'=>$form_state['values']['datasource']));
        $exportStream = new GD\Sync\Export\ExportStream();

        $exportController = new \GD\Sync\Export\ExportController();
        $exportController->export($exportStream,$exportContext);

        $export = json_encode($exportStream->flush());

    } else {
        $export = null;
    }

    $form['export'] = array(
        '#type' => 'fieldset',
        '#title' => t('Datasource Export'),
        '#description' => 'I will create a a dump of a datasource'
    );

    $form['export']['datasource'] = array(
        '#type' => 'select',
        '#title' => t('Select Datasource'),
        '#description' => 'The datasource to export.',
        '#options' => gd_sync_get_datasource_options()
    );

    $form['export']['actions'] = array(
        '#type' => 'fieldset',
        '#weight' => 0,
        '#collapsible' => false,
        '#collapsed' => false
    );

    $form['export']['actions']['action'] = array(
        '#type' => 'button',
        '#value' => t('Export'),
        '#ajax' => array(
            'callback' => 'gd_sync_export_ajax_callback',
            'wrapper' => 'sync-export-wrapper',
            'method' => 'replace',
            'effect' => 'fade'
        )
    );

    $form['export']['actions']['reset'] = array(
        '#type' => 'button',
        '#value' => t('Reset'),
        '#attributes' => array('onclick' => 'location.href=\'/admin/structure/govdashboard/sync\';')
    );

    $form['export']['data'] = array(
        '#markup' => '<div id="sync-export-wrapper" style="margin-top: 20px;"><strong>Result:</strong><br/><textarea style="background-color: #eee; border: 2px dashed #aaa; padding: 10px;" cols="160" rows="10">'.check_plain($export).'</textarea></div>'
    );

    return $form;
}
/**
 * @param $datasourceName
 * @return array|services_error
 */
function gd_sync_resource_export ( $datasourceName ) {
    try {
        $exportContext = new GD\Sync\Export\ExportContext(array('datasourceName'=>$datasourceName));
        $exportStream = new GD\Sync\Export\ExportStream();

        $exportController = new \GD\Sync\Export\ExportController();
        $exportController->export($exportStream,$exportContext);

        return $exportStream->flush();
    } catch ( Exception $e ) {
        return gd_admin_ui_service_exception_handler($e);
    }
}