<commit_before>import React from 'react'
import { PropTypes } from 'react'
import Text from './Text'
import Textarea from './Textarea'
// import Select from './Select`'
import File from './File'
import Checkbox from './Checkbox'
import FormContributors from './FormContributors'
import FormRecorders from './FormRecorders'
import FormMoveButtons from './FormMoveButtons'
import FormRemoveButton from './FormRemoveButton'

import ProviderHelpers from 'common/ProviderHelpers'
import IntlService from 'views/services/intl'
// import DocumentListView from 'views/components/Document/DocumentListView'
import Preview from 'views/components/Editor/Preview'
// see about dropping:
import selectn from 'selectn'
import provide from 'react-redux-provide'
const intl = IntlService.instance
const { array, func, object, number, string, element } = PropTypes
export class FormRelatedVideo extends React.Component {
  STATE_LOADING = 0
  STATE_DEFAULT = 1
  STATE_CREATE = 2
  STATE_CREATED = 3
  // STATE_EDIT = 4
  STATE_BROWSE = 5

  static propTypes = {
    name: string,
    className: string,
    groupName: string,
    id: number,
    idDescribedbyItemBrowse: string,
    idDescribedByItemMove: string,
    index: number,
    textBtnRemoveItem: string,
    textBtnMoveItemUp: string,
    textBtnMoveItemDown: string,
    textBtnCreateItem: string,
    // textBtnEditItem: string,
    textBtnSelectExistingItems: string,
    textLabelItemSearch: string,
    textLegendItem: string,
    handleClickCreateItem: func,
    // handleClickEditItem: func,
    handleClickSelectItem: func,
    handleClickRemoveItem: func,
    handleClickMoveItemUp: func,
    handleClickMoveItemDown: func,
    handleItemSelected: func,
    componentState: number,
    value: string,
    DISABLED_SORT_COLS: array,
    DEFAULT_PAGE: number,
    DEFAULT_PAGE_SIZE: number,
    DEFAULT_LANGUAGE: string,
    DEFAULT_SORT_COL: string,
    DEFAULT_SORT_TYPE: string,
    DIALECT_PATH: string.isRequired,
    selectMediaComponent: element.isRequired,
    // NOTE: COMING FROM REDUX/PROVIDER
    computeVideo: object.isRequired,
    createVideo: func.isRequired,
    // NOTE: COMING FROM PARENT COMPONENT, NOT REDUX/PROVIDER
    computeDialectFromParent: object.isRequired,
  }
  static defaultProps = {
    className: 'FormRelatedVideo',
    groupName: 'FormRelatedVideo__group',
    id: -1,
    index: 0,
    componentState: 0,
    handleClickCreateItem: () => {},
    // handleClickEditItem: () => {},
    handleClickSelectItem: () => {},
    handleClickRemoveItem: () => {},
    handleClickMoveItemUp: () => {},
    handleClickMoveItemDown: () => {},
    handleItemSelected: () => {},
    DISABLED_SORT_COLS: ['state'],
    DEFAULT_PAGE: 1,
    DEFAULT_PAGE_SIZE: 100,
    DEFAULT_LANGUAGE: 'english',
    DEFAULT_SORT_COL: 'dc:title',
    DEFAULT_SORT_TYPE: 'asc',
    selectMediaComponent: null,
  }
  state = {
    componentState: this.props.componentState,
    createItemName: '',
    createItemDescription: '',
    createItemFile: {},
    createItemIsShared: false,
    createItemIsChildFocused: false,
    createItemContributors: [],
    createItemRecorders: [],
    pathOrId: undefined,
  }

  CONTRIBUTOR_PATH = undefined

  //   AFTER SUBMITTING NEW CONTRIBUTOR
  // ProviderHelpers.getEntry(nextProps.computeContributor, this.state.contributorPath).response

  render() {
    const {
      className,
      name,
      id,
      // idDescribedbyItemBrowse,
      idDescribedByItemMove,
      index,
      textBtnRemoveItem,
      textBtnMoveItemUp,
      textBtnMoveItemDown,
      textBtnCreateItem,
      // textBtnEditItem,
      textBtnSelectExistingItems,
      // textLabelItemSearch,
      textLegendItem,
      // handleClickSelectItem,
      handleClickRemoveItem,
      handleClickMoveItemUp,
      handleClickMoveItemDown,
      // value,
    } = this.props

    let componentContent = null
    const computeCreate = ProviderHelpers.getEntry(this.props.computeVideo, this.state.pathOrId)
    const isFetching = selectn('isFetching', computeCreate)
    const isSuccess = selectn('success', computeCreate)
    // let createdUid = null
    // let createdTitle = null
    // let createdPath = null
    // if (isSuccess) {
    //   createdUid = selectn(['response', 'uid'], computeCreate)
    //   createdTitle = selectn(['response', 'title'], computeCreate)
    //   createdPath = selectn(['response', 'path'], computeCreate)
    // }
    const _handleItemSelectedOrCreated = (selected) => {
      this.props.handleItemSelected(selected, () => {
        handleClickRemoveItem(id)
      })
    }

    if (isSuccess) {
      // Note: deletes the in-progress/newly added item and inserts the just created item
      _handleItemSelectedOrCreated(selectn('response', computeCreate))
    }

    switch (this.state.componentState) {
      case this.STATE_CREATE: {
        let formStatus = null
        if (isFetching) {
          formStatus = (

              {intl.trans('views.components.editor.uploading_message', 'Uploading... Please be patient...', 'first')}

          )
        }

        // CREATE AUDIO ------------------------------------
        componentContent = (

Create new video

            {/* Name ------------- */}
            <Text
              className={this.props.groupName}
              id={`${className}__Contributor${index}__NewName`}
              labelText="Name of video"
              name={`${name}[${index}]__NewName`}
              value=""
              handleChange={(data) => {
                this.setState({ createItemName: data })
              }}
            />
            {/* Description --------------- */}
            <Textarea
              className={this.props.groupName}
              id="CreateVideo__Description"
              labelText="Description of video"
              name="dc:description"
              value=""
              handleChange={(data) => {
                this.setState({ createItemDescription: data })
              }}
            />

            {/* File --------------- */}
            <File
              className={this.props.groupName}
              id="CreateVideo__File"
              labelText="Upload video"
              name="file"
              value=""
              handleChange={(data) => {
                this.setState({ createItemFile: data })
              }}
            />

            {/* Shared --------------- */}
            <Checkbox
              className={this.props.groupName}
              id="CreateVideo__Shared"
              labelText="Share this video across dialects"
              name="fvm:shared"
              handleChange={(data) => {
                this.setState({ createItemIsShared: data })
              }}
            />
            {/* Child focused --------------- */}
            <Checkbox
              className={this.props.groupName}
              id="CreateVideo__ChildFocused"
              labelText="Video is child focused"
              name="fvm:child_focused"
              handleChange={(data) => {
                this.setState({ createItemIsChildFocused: data })
              }}
            />

            {/* Contributors: fvm:source --------------- */}
            <FormContributors
              className={this.props.groupName}
              name="fv:source"
              textInfo="Contributors who helped create the video."
              handleItemsUpdate={(data) => {
                this.setState({ createItemContributors: data })
              }}
            />

            {/* Recorders: fvm:recorder --------------- */}
            <FormRecorders
              className={this.props.groupName}
              name="fvm:recorder"
              textInfo="Recorders who helped create the video."
              handleItemsUpdate={(data) => {
                this.setState({ createItemRecorders: data })
              }}
            />

            {/* BTN: Create contributor ------------- */}
            <button
              disabled={isFetching || isSuccess}
              type="button"
              onClick={(event) => {
                event.preventDefault()
                this._handleCreateItemSubmit()
              }}
            >
              Create new video
            </button>

            {/* BTN: Cancel, go back ------------- */}
            <button
              disabled={isFetching || isSuccess}
              type="button"
              onClick={() => {
                this.setState({
                  componentState: this.STATE_DEFAULT,
                })
              }}
            >
              {"Cancel, don't create new video"}
            </button>
            {formStatus}

        )
        break
      }
      case this.STATE_CREATED: {
        // AUDIO CREATED/SELECTED ------------------------------------
        let previewInput = 'Something went wrong!'
        if (id !== -1) {
          previewInput = (

              <input type="hidden" name={name} value={id} />
              <Preview id={id} type="FVVideo" />

          )
        }
        componentContent = (

              <FormMoveButtons
                id={id}
                idDescribedByItemMove={idDescribedByItemMove}
                textBtnMoveItemUp={textBtnMoveItemUp}
                textBtnMoveItemDown={textBtnMoveItemDown}
                handleClickMoveItemUp={handleClickMoveItemUp}
                handleClickMoveItemDown={handleClickMoveItemDown}
              />
              <FormRemoveButton
                id={id}
                textBtnRemoveItem={textBtnRemoveItem}
                handleClickRemoveItem={handleClickRemoveItem}
              />

            {previewInput}

        )
        break
      }
      // case this.STATE_EDIT:
      //   // EDITING A CONTRIBUTOR ------------------------------------
      //   componentContent = (
      //

      //
Editing contributor

      //       {/* Name ------------- */}
      //       <Text
      //         className={this.props.groupName}
      //         id={`${className}__Contributor${index}__EditName`}
      //         labelText="Related Video name"
      //         name={`${name}[${index}]__EditName`}
      //         value="[some prefilled value]"
      //       />

      //       {/* Description ------------- */}
      //       <Textarea
      //         className={this.props.groupName}
      //         id={`${className}__Contributor${index}__EditDescription`}
      //         labelText="Related Video description"
      //         name={`${name}[${index}]__EditDescription`}
      //         value=""
      //       />

      //       {/* BTN: Create contributor ------------- */}
      //       <button
      //         type="button"
      //         onClick={(event) => {
      //           event.preventDefault()
      //           this._handleCreateItemSubmit()
      //         }}
      //       >
      //         Update contributor
      //       </button>

      //       {/* BTN: Cancel, go back ------------- */}
      //       <button
      //         type="button"
      //         onClick={() => {
      //           this.setState({
      //             componentState: this.STATE_CREATED,
      //           })
      //         }}
      //       >
      //         {"Cancel, don't update contributor"}
      //       </button>
      //

      //   )
      //   break
      // case this.STATE_BROWSE: {
      //   // TODO: REMOVE? USING OLD MODAL CODE INSTEAD
      //   // Select from existing audio  ------------------------------------

      //   const { computeResourcesFromParent } = this.props
      //   const _computeResources = ProviderHelpers.getEntry(computeResourcesFromParent, '/FV/Workspaces/')
      //   const items =
      //     selectn('response.entries', _computeResources) || selectn('response_prev.entries', _computeResources) || []
      //   let audioExisting = []

      //   audioExisting = items.map((_element, i) => {
      //     const uid = _element.uid
      //     const audioId = `related_audio_${uid}`
      //     return (
      //       <div className={`${className}__browseItem`} key={i}>
      //         <div className={`${className}__browseItemGroup1`}>
      //           <input
      //             className={`${className}__browseItemRadio`}
      //             type="radio"
      //             id={audioId}
      //             name="related_audio"
      //             value={uid}
      //           />
      //

      //         <div className={`${className}__browseItemGroup2`}>
      //           {`Select '${_element.title}'`}
      //           <audio src={selectn('properties.file:content.data', _element)} preload="none" controls />
      //

      //

      //     )
      //   })

      //   componentContent = (
      //

      //
 {
      //           this.setState({
      //             relatedAudioUid: event.target.value,
      //           })
      //         }}
      //       >
      //         {audioExisting}
      //

      //       {/* Save/select contributor ------------- */}
      //       <button
      //         type="button"
      //         disabled={this.state.relatedAudioUid === undefined}
      //         onClick={() => {
      //           this.setState({
      //             componentState: this.STATE_CREATED,
      //             audioUid: this.state.relatedAudioUid,
      //           })
      //         }}
      //       >
      //         Add selected Related Video
      //       </button>

      //       {/* BTN: Cancel, go back ------------- */}
      //       <button
      //         type="button"
      //         onClick={() => {
      //           this.setState({
      //             componentState: this.STATE_DEFAULT,
      //           })
      //         }}
      //       >
      //         {"Cancel, don't add Related Video"}
      //       </button>
      //

      //   )
      //   break
      // }
      default: {
        // INITIAL STATE ------------------------------------
        const { computeDialectFromParent, selectMediaComponent } = this.props
        const SelectMediaComponent = selectMediaComponent
        componentContent = (

              {/* <FormMoveButtons
                id={id}
                idDescribedByItemMove={idDescribedByItemMove}
                textBtnMoveItemUp={textBtnMoveItemUp}
                textBtnMoveItemDown={textBtnMoveItemDown}
                handleClickMoveItemUp={handleClickMoveItemUp}
                handleClickMoveItemDown={handleClickMoveItemDown}
              /> */}
              <FormRemoveButton
                id={id}
                textBtnRemoveItem={textBtnRemoveItem}
                handleClickRemoveItem={handleClickRemoveItem}
              />

            {/* Create contributor */}
            <button
              type="button"
              onClick={() => {
                this._handleClickCreateItem()
              }}
            >
              {textBtnCreateItem}
            </button>

            {/* Browse/select contributor */}
            {/* <button
              aria-describedby={idDescribedbyItemBrowse}
              onClick={() => {
                this._handleClickSelectItem()
              }}
              type="button"
            >
              {textBtnSelectExistingItems}
            </button> */}

            <SelectMediaComponent
              type={'FVVideo'}
              label={textBtnSelectExistingItems}
              onComplete={_handleItemSelectedOrCreated}
              dialect={selectn('response', computeDialectFromParent)}
            />

        )
      }
    }
    return (
      <fieldset className={`${className} ${this.props.groupName}`}>
        <legend>{textLegendItem}</legend>
        {componentContent}
      </fieldset>
    )
  }
  _handleClickCreateItem = () => {
    const { handleClickCreateItem } = this.props
    this.setState(
      {
        componentState: this.STATE_CREATE,
      },
      () => {
        handleClickCreateItem()
      }
    )
  }
  // _handleClickEditItem = (id) => {
  //   const { handleClickEditItem } = this.props
  //   this.setState(
  //     {
  //       componentState: this.STATE_EDIT,
  //     },
  //     () => {
  //       handleClickEditItem(id)
  //     }
  //   )
  // }
  _handleSubmitExistingItem = (createItemUid) => {
    this.setState(
      {
        componentState: this.STATE_CREATED,
        contributorUid: createItemUid,
      },
      () => {}
    )
  }

  async _handleCreateItemSubmit() {
    const {
      createItemName,
      createItemDescription,
      createItemFile,
      createItemIsShared,
      createItemIsChildFocused,
      createItemContributors,
      createItemRecorders,
    } = this.state

    const docParams = {
      type: 'FVVideo',
      name: createItemName,
      properties: {
        'dc:title': createItemName,
        'dc:description': createItemDescription,
        'fvm:shared': createItemIsShared,
        'fvm:child_focused': createItemIsChildFocused,
        'fvm:recorder': createItemRecorders['fvm:recorder'] || [],
        'fvm:source': createItemContributors['fvm:source'] || [],
      },
    }

    const timestamp = Date.now()
    const { DIALECT_PATH } = this.props
    this.props.createVideo(`${DIALECT_PATH}/Resources`, docParams, createItemFile, timestamp)
    const pathOrId = `${DIALECT_PATH}/Resources/${createItemName}.${timestamp}`
    this.setState({ pathOrId })
  }
}

export default provide(FormRelatedVideo)
<commit_msg>Drop commented out code<commit_after>import React from 'react'
import { PropTypes } from 'react'
import Text from './Text'
import Textarea from './Textarea'
// import Select from './Select`'
import File from './File'
import Checkbox from './Checkbox'
import FormContributors from './FormContributors'
import FormRecorders from './FormRecorders'
import FormMoveButtons from './FormMoveButtons'
import FormRemoveButton from './FormRemoveButton'

import ProviderHelpers from 'common/ProviderHelpers'
import IntlService from 'views/services/intl'
// import DocumentListView from 'views/components/Document/DocumentListView'
import Preview from 'views/components/Editor/Preview'
// see about dropping:
import selectn from 'selectn'
import provide from 'react-redux-provide'
const intl = IntlService.instance
const { array, func, object, number, string, element } = PropTypes
export class FormRelatedVideo extends React.Component {
  STATE_LOADING = 0
  STATE_DEFAULT = 1
  STATE_CREATE = 2
  STATE_CREATED = 3
  // STATE_EDIT = 4
  STATE_BROWSE = 5

  static propTypes = {
    name: string,
    className: string,
    groupName: string,
    id: number,
    idDescribedbyItemBrowse: string,
    idDescribedByItemMove: string,
    index: number,
    textBtnRemoveItem: string,
    textBtnMoveItemUp: string,
    textBtnMoveItemDown: string,
    textBtnCreateItem: string,
    // textBtnEditItem: string,
    textBtnSelectExistingItems: string,
    textLabelItemSearch: string,
    textLegendItem: string,
    handleClickCreateItem: func,
    // handleClickEditItem: func,
    handleClickSelectItem: func,
    handleClickRemoveItem: func,
    handleClickMoveItemUp: func,
    handleClickMoveItemDown: func,
    handleItemSelected: func,
    componentState: number,
    value: string,
    DISABLED_SORT_COLS: array,
    DEFAULT_PAGE: number,
    DEFAULT_PAGE_SIZE: number,
    DEFAULT_LANGUAGE: string,
    DEFAULT_SORT_COL: string,
    DEFAULT_SORT_TYPE: string,
    DIALECT_PATH: string.isRequired,
    selectMediaComponent: element.isRequired,
    // NOTE: COMING FROM REDUX/PROVIDER
    computeVideo: object.isRequired,
    createVideo: func.isRequired,
    // NOTE: COMING FROM PARENT COMPONENT, NOT REDUX/PROVIDER
    computeDialectFromParent: object.isRequired,
  }
  static defaultProps = {
    className: 'FormRelatedVideo',
    groupName: 'FormRelatedVideo__group',
    id: -1,
    index: 0,
    componentState: 0,
    handleClickCreateItem: () => {},
    // handleClickEditItem: () => {},
    handleClickSelectItem: () => {},
    handleClickRemoveItem: () => {},
    handleClickMoveItemUp: () => {},
    handleClickMoveItemDown: () => {},
    handleItemSelected: () => {},
    DISABLED_SORT_COLS: ['state'],
    DEFAULT_PAGE: 1,
    DEFAULT_PAGE_SIZE: 100,
    DEFAULT_LANGUAGE: 'english',
    DEFAULT_SORT_COL: 'dc:title',
    DEFAULT_SORT_TYPE: 'asc',
    selectMediaComponent: null,
  }
  state = {
    componentState: this.props.componentState,
    createItemName: '',
    createItemDescription: '',
    createItemFile: {},
    createItemIsShared: false,
    createItemIsChildFocused: false,
    createItemContributors: [],
    createItemRecorders: [],
    pathOrId: undefined,
  }

  CONTRIBUTOR_PATH = undefined

  //   AFTER SUBMITTING NEW CONTRIBUTOR
  // ProviderHelpers.getEntry(nextProps.computeContributor, this.state.contributorPath).response

  render() {
    const {
      className,
      name,
      id,
      // idDescribedbyItemBrowse,
      idDescribedByItemMove,
      index,
      textBtnRemoveItem,
      textBtnMoveItemUp,
      textBtnMoveItemDown,
      textBtnCreateItem,
      // textBtnEditItem,
      textBtnSelectExistingItems,
      // textLabelItemSearch,
      textLegendItem,
      // handleClickSelectItem,
      handleClickRemoveItem,
      handleClickMoveItemUp,
      handleClickMoveItemDown,
      // value,
    } = this.props

    let componentContent = null
    const computeCreate = ProviderHelpers.getEntry(this.props.computeVideo, this.state.pathOrId)
    const isFetching = selectn('isFetching', computeCreate)
    const isSuccess = selectn('success', computeCreate)
    // let createdUid = null
    // let createdTitle = null
    // let createdPath = null
    // if (isSuccess) {
    //   createdUid = selectn(['response', 'uid'], computeCreate)
    //   createdTitle = selectn(['response', 'title'], computeCreate)
    //   createdPath = selectn(['response', 'path'], computeCreate)
    // }
    const _handleItemSelectedOrCreated = (selected) => {
      this.props.handleItemSelected(selected, () => {
        handleClickRemoveItem(id)
      })
    }

    if (isSuccess) {
      // Note: deletes the in-progress/newly added item and inserts the just created item
      _handleItemSelectedOrCreated(selectn('response', computeCreate))
    }

    switch (this.state.componentState) {
      case this.STATE_CREATE: {
        let formStatus = null
        if (isFetching) {
          formStatus = (

              {intl.trans('views.components.editor.uploading_message', 'Uploading... Please be patient...', 'first')}

          )
        }

        // CREATE AUDIO ------------------------------------
        componentContent = (

Create new video

            {/* Name ------------- */}
            <Text
              className={this.props.groupName}
              id={`${className}__Contributor${index}__NewName`}
              labelText="Name of video"
              name={`${name}[${index}]__NewName`}
              value=""
              handleChange={(data) => {
                this.setState({ createItemName: data })
              }}
            />
            {/* Description --------------- */}
            <Textarea
              className={this.props.groupName}
              id="CreateVideo__Description"
              labelText="Description of video"
              name="dc:description"
              value=""
              handleChange={(data) => {
                this.setState({ createItemDescription: data })
              }}
            />

            {/* File --------------- */}
            <File
              className={this.props.groupName}
              id="CreateVideo__File"
              labelText="Upload video"
              name="file"
              value=""
              handleChange={(data) => {
                this.setState({ createItemFile: data })
              }}
            />

            {/* Shared --------------- */}
            <Checkbox
              className={this.props.groupName}
              id="CreateVideo__Shared"
              labelText="Share this video across dialects"
              name="fvm:shared"
              handleChange={(data) => {
                this.setState({ createItemIsShared: data })
              }}
            />
            {/* Child focused --------------- */}
            <Checkbox
              className={this.props.groupName}
              id="CreateVideo__ChildFocused"
              labelText="Video is child focused"
              name="fvm:child_focused"
              handleChange={(data) => {
                this.setState({ createItemIsChildFocused: data })
              }}
            />

            {/* Contributors: fvm:source --------------- */}
            <FormContributors
              className={this.props.groupName}
              name="fv:source"
              textInfo="Contributors who helped create the video."
              handleItemsUpdate={(data) => {
                this.setState({ createItemContributors: data })
              }}
            />

            {/* Recorders: fvm:recorder --------------- */}
            <FormRecorders
              className={this.props.groupName}
              name="fvm:recorder"
              textInfo="Recorders who helped create the video."
              handleItemsUpdate={(data) => {
                this.setState({ createItemRecorders: data })
              }}
            />

            {/* BTN: Create contributor ------------- */}
            <button
              disabled={isFetching || isSuccess}
              type="button"
              onClick={(event) => {
                event.preventDefault()
                this._handleCreateItemSubmit()
              }}
            >
              Create new video
            </button>

            {/* BTN: Cancel, go back ------------- */}
            <button
              disabled={isFetching || isSuccess}
              type="button"
              onClick={() => {
                this.setState({
                  componentState: this.STATE_DEFAULT,
                })
              }}
            >
              {"Cancel, don't create new video"}
            </button>
            {formStatus}

        )
        break
      }
      case this.STATE_CREATED: {
        // AUDIO CREATED/SELECTED ------------------------------------
        let previewInput = 'Something went wrong!'
        if (id !== -1) {
          previewInput = (

              <Preview id={id} type="FVVideo" />

          )
        }
        componentContent = (

              <FormMoveButtons
                id={id}
                idDescribedByItemMove={idDescribedByItemMove}
                textBtnMoveItemUp={textBtnMoveItemUp}
                textBtnMoveItemDown={textBtnMoveItemDown}
                handleClickMoveItemUp={handleClickMoveItemUp}
                handleClickMoveItemDown={handleClickMoveItemDown}
              />
              <FormRemoveButton
                id={id}
                textBtnRemoveItem={textBtnRemoveItem}
                handleClickRemoveItem={handleClickRemoveItem}
              />

            {previewInput}

        )
        break
      }
      // case this.STATE_EDIT:
      //   // EDITING A CONTRIBUTOR ------------------------------------
      //   componentContent = (
      //

      //
Editing contributor

      //       {/* Name ------------- */}
      //       <Text
      //         className={this.props.groupName}
      //         id={`${className}__Contributor${index}__EditName`}
      //         labelText="Related Video name"
      //         name={`${name}[${index}]__EditName`}
      //         value="[some prefilled value]"
      //       />

      //       {/* Description ------------- */}
      //       <Textarea
      //         className={this.props.groupName}
      //         id={`${className}__Contributor${index}__EditDescription`}
      //         labelText="Related Video description"
      //         name={`${name}[${index}]__EditDescription`}
      //         value=""
      //       />

      //       {/* BTN: Create contributor ------------- */}
      //       <button
      //         type="button"
      //         onClick={(event) => {
      //           event.preventDefault()
      //           this._handleCreateItemSubmit()
      //         }}
      //       >
      //         Update contributor
      //       </button>

      //       {/* BTN: Cancel, go back ------------- */}
      //       <button
      //         type="button"
      //         onClick={() => {
      //           this.setState({
      //             componentState: this.STATE_CREATED,
      //           })
      //         }}
      //       >
      //         {"Cancel, don't update contributor"}
      //       </button>
      //

      //   )
      //   break
      // case this.STATE_BROWSE: {
      //   // TODO: REMOVE? USING OLD MODAL CODE INSTEAD
      //   // Select from existing audio  ------------------------------------

      //   const { computeResourcesFromParent } = this.props
      //   const _computeResources = ProviderHelpers.getEntry(computeResourcesFromParent, '/FV/Workspaces/')
      //   const items =
      //     selectn('response.entries', _computeResources) || selectn('response_prev.entries', _computeResources) || []
      //   let audioExisting = []

      //   audioExisting = items.map((_element, i) => {
      //     const uid = _element.uid
      //     const audioId = `related_audio_${uid}`
      //     return (
      //       <div className={`${className}__browseItem`} key={i}>
      //         <div className={`${className}__browseItemGroup1`}>
      //           <input
      //             className={`${className}__browseItemRadio`}
      //             type="radio"
      //             id={audioId}
      //             name="related_audio"
      //             value={uid}
      //           />
      //

      //         <div className={`${className}__browseItemGroup2`}>
      //           {`Select '${_element.title}'`}
      //           <audio src={selectn('properties.file:content.data', _element)} preload="none" controls />
      //

      //

      //     )
      //   })

      //   componentContent = (
      //

      //
 {
      //           this.setState({
      //             relatedAudioUid: event.target.value,
      //           })
      //         }}
      //       >
      //         {audioExisting}
      //

      //       {/* Save/select contributor ------------- */}
      //       <button
      //         type="button"
      //         disabled={this.state.relatedAudioUid === undefined}
      //         onClick={() => {
      //           this.setState({
      //             componentState: this.STATE_CREATED,
      //             audioUid: this.state.relatedAudioUid,
      //           })
      //         }}
      //       >
      //         Add selected Related Video
      //       </button>

      //       {/* BTN: Cancel, go back ------------- */}
      //       <button
      //         type="button"
      //         onClick={() => {
      //           this.setState({
      //             componentState: this.STATE_DEFAULT,
      //           })
      //         }}
      //       >
      //         {"Cancel, don't add Related Video"}
      //       </button>
      //

      //   )
      //   break
      // }
      default: {
        // INITIAL STATE ------------------------------------
        const { computeDialectFromParent, selectMediaComponent } = this.props
        const SelectMediaComponent = selectMediaComponent
        componentContent = (

              {/* <FormMoveButtons
                id={id}
                idDescribedByItemMove={idDescribedByItemMove}
                textBtnMoveItemUp={textBtnMoveItemUp}
                textBtnMoveItemDown={textBtnMoveItemDown}
                handleClickMoveItemUp={handleClickMoveItemUp}
                handleClickMoveItemDown={handleClickMoveItemDown}
              /> */}
              <FormRemoveButton
                id={id}
                textBtnRemoveItem={textBtnRemoveItem}
                handleClickRemoveItem={handleClickRemoveItem}
              />

            {/* Create contributor */}
            <button
              type="button"
              onClick={() => {
                this._handleClickCreateItem()
              }}
            >
              {textBtnCreateItem}
            </button>

            {/* Browse/select contributor */}
            {/* <button
              aria-describedby={idDescribedbyItemBrowse}
              onClick={() => {
                this._handleClickSelectItem()
              }}
              type="button"
            >
              {textBtnSelectExistingItems}
            </button> */}

            <SelectMediaComponent
              type={'FVVideo'}
              label={textBtnSelectExistingItems}
              onComplete={_handleItemSelectedOrCreated}
              dialect={selectn('response', computeDialectFromParent)}
            />

        )
      }
    }
    return (
      <fieldset className={`${className} ${this.props.groupName}`}>
        <legend>{textLegendItem}</legend>
        {componentContent}
      </fieldset>
    )
  }
  _handleClickCreateItem = () => {
    const { handleClickCreateItem } = this.props
    this.setState(
      {
        componentState: this.STATE_CREATE,
      },
      () => {
        handleClickCreateItem()
      }
    )
  }
  // _handleClickEditItem = (id) => {
  //   const { handleClickEditItem } = this.props
  //   this.setState(
  //     {
  //       componentState: this.STATE_EDIT,
  //     },
  //     () => {
  //       handleClickEditItem(id)
  //     }
  //   )
  // }
  _handleSubmitExistingItem = (createItemUid) => {
    this.setState(
      {
        componentState: this.STATE_CREATED,
        contributorUid: createItemUid,
      },
      () => {}
    )
  }

  async _handleCreateItemSubmit() {
    const {
      createItemName,
      createItemDescription,
      createItemFile,
      createItemIsShared,
      createItemIsChildFocused,
      createItemContributors,
      createItemRecorders,
    } = this.state

    const docParams = {
      type: 'FVVideo',
      name: createItemName,
      properties: {
        'dc:title': createItemName,
        'dc:description': createItemDescription,
        'fvm:shared': createItemIsShared,
        'fvm:child_focused': createItemIsChildFocused,
        'fvm:recorder': createItemRecorders['fvm:recorder'] || [],
        'fvm:source': createItemContributors['fvm:source'] || [],
      },
    }

    const timestamp = Date.now()
    const { DIALECT_PATH } = this.props
    this.props.createVideo(`${DIALECT_PATH}/Resources`, docParams, createItemFile, timestamp)
    const pathOrId = `${DIALECT_PATH}/Resources/${createItemName}.${timestamp}`
    this.setState({ pathOrId })
  }
}

export default provide(FormRelatedVideo)
<|endoftext|>


<commit_before>var https = require('https'),
    http  = require('http'),
    util  = require('util'),
    path  = require('path'),
    fs    = require('fs'),
    fixturesDir = path.join(__dirname, 'test', 'fixtures'),
    httpProxy = require('./lib/http-proxy');
//forward to web01's https proxy in the browser
 http.createServer(function (req, res) {
  res.writeHead(301, { 'Content-Type': 'text/plain' ,
                       'Location'    : 'https://'+'198.135.14.61'+req.url});
  												//198.135.15.93 for dev, 198.135.15.19 for test
     res.end('Redirecting to Web01\n');
  }).listen(8892);

 http.createServer(function (req, res) {
  res.writeHead(301, { 'Content-Type': 'text/plain' ,
                       'Location'    : 'https://'+'198.135.14.61'+req.url});
                          //198.135.15.93 for dev, 198.135.15.19 for test
     res.end('Redirecting to Web01\n');
  }).listen(80);
//
// proxy HTTPS to Web01 internal ip
//
httpProxy.createServer({
  target: {
    host: '192.168.0.3',
    port: 8892
  },
  changeOrigin: false,
  ssl: {
    cert : fs.readFileSync(path.join(__dirname, './fakecerts/ca2/', 'server2.crt')),
     key  : fs.readFileSync(path.join(__dirname, './fakecerts', 'server.key')),
     ca   : fs.readFileSync(path.join(__dirname, './fakecerts/ca2/', 'ca2.crt')),
     passphrase: 'tae123456'
  }
}).listen(443);

util.puts('http proxy server ' + 'started '+ 'on port ' + '443 ');<commit_msg> test<commit_after>var https = require('https'),
    http  = require('http'),
    http2  = require('http'),
    util  = require('util'),
    path  = require('path'),
    fs    = require('fs'),
    fixturesDir = path.join(__dirname, 'test', 'fixtures'),
    httpProxy = require('./lib/http-proxy');
//forward to web01's https proxy in the browser
 http.createServer(function (req, res) {
  res.writeHead(301, { 'Content-Type': 'text/plain' ,
                       'Location'    : 'https://'+'198.135.14.61'+req.url});
  												//198.135.15.93 for dev, 198.135.15.19 for test
     res.end('Redirecting to Web01\n');
  }).listen(8892);

 http2.createServer(function (req, res) {
  res.writeHead(301, { 'Content-Type': 'text/plain' ,
                       'Location'    : 'https://'+'198.135.14.61'+req.url});
                          //198.135.15.93 for dev, 198.135.15.19 for test
     res.end('Redirecting to Web01\n');
  }).listen(80);
//
// proxy HTTPS to Web01 internal ip
//
httpProxy.createServer({
  target: {
    host: '192.168.0.3',
    port: 8892
  },
  changeOrigin: false,
  ssl: {
    cert : fs.readFileSync(path.join(__dirname, './fakecerts/ca2/', 'server2.crt')),
     key  : fs.readFileSync(path.join(__dirname, './fakecerts', 'server.key')),
     ca   : fs.readFileSync(path.join(__dirname, './fakecerts/ca2/', 'ca2.crt')),
     passphrase: 'tae123456'
  }
}).listen(443);

util.puts('http proxy server ' + 'started '+ 'on port ' + '80,8892 ->443 ');<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { View, Image, TouchableHighlight } from 'react-native'
import {
  Content, Body,
  Card, CardItem,
  Button,
  Icon, Text
} from 'native-base'
import {Avatar} from 'react-native-material-ui';

export default class MissionBoard extends Component {
  render = () => {
    const { navigate } = this.props.navigation
    return (
      <Content>
        {[,...Array(5)].map((x, index) => (
          <Card key={index}>
            <CardItem onPress={() => navigate('MissionDetail')}>
              <Body>
                <View style={{ flexDirection: 'row', flex: 1 }}>
                  {/*Center align the picture*/}
                  <View style={{justifyContent: 'center', alignItems: 'center'}}><Image source={require('../Fetch.png')} /></View>
                  {/*Align the product attributes*/}
                  <View style={{ flexDirection: 'column', flex: 1, padding: 10 }}>
                    <Text style={{ fontSize: 20 }}>Uniqlo Flannel</Text>
                    <Text>3 hours left</Text>
                    <View style={{ flexDirection: 'row', flex: 1, paddingVertical: 5 }}>
                      <View style={{ height: 50, width: 55 }}>
                        <Avatar text="E" size={40} />
                      </View>
                      <View style={{ flexDirection: 'column', flex: 1 }}>
                        <Text>Edmund Pan</Text>
                        <View style={{ flexDirection: 'row', flex: 1 }}>
                          {[,...Array(5)].map((x, index) => (
                            <Icon name="star" style={{ fontSize: 20 }} key={index}/>
                          ))}
                        </View>
                      </View>
                    </View>
                    <View>
                      <Button primary block onPress={() => navigate('TaskForm')}>
                        <Text>Join</Text>
                      </Button>
                    </View>
                  </View>
                </View>
              </Body>
            </CardItem>
          </Card>
        ))}
      </Content>
    )
  }
}
<commit_msg>extract fake data from missionboard to const<commit_after>import React, { Component } from 'react'
import { View, Image, TouchableHighlight } from 'react-native'
import {
  Content, Body,
  Card, CardItem,
  Button,
  Icon, Text,
  List
} from 'native-base'
import {Avatar} from 'react-native-material-ui';

const fakeMissions = [
  { name: 'Uniqlo Flannel', deadline: '3 hours left', username: 'Yihao' },
  { name: 'Uniqlo Flannel', deadline: '3 hours left', username: 'Yihao' },
  { name: 'Uniqlo Flannel', deadline: '3 hours left', username: 'Yihao' },
  { name: 'Uniqlo Flannel', deadline: '3 hours left', username: 'Yihao' },
  { name: 'Uniqlo Flannel', deadline: '3 hours left', username: 'Yihao' }
]

export default class MissionBoard extends Component {
  state = {
    missions: fakeMissions
  }
  render = () => {
    const { navigate } = this.props.navigation
    return (
      <Content>
        <List dataArray={this.state.missions} renderRow={mission => (
          <Card>
            <CardItem onPress={() => navigate('MissionDetail')}>
              <Body>
                <View style={{ flexDirection: 'row', flex: 1 }}>
                  {/*Center align the picture*/}
                  <View style={{justifyContent: 'center', alignItems: 'center'}}><Image source={require('../Fetch.png')} /></View>
                  {/*Align the product attributes*/}
                  <View style={{ flexDirection: 'column', flex: 1, padding: 10 }}>
                    <Text style={{ fontSize: 20 }}>{mission.name}</Text>
                    <Text>{mission.deadline}</Text>
                    <View style={{ flexDirection: 'row', flex: 1, paddingVertical: 5 }}>
                      <View style={{ height: 50, width: 55 }}>
                        <Avatar text={mission.username[0]} size={40} />
                      </View>
                      <View style={{ flexDirection: 'column', flex: 1 }}>
                        <Text>{mission.username}</Text>
                        <View style={{ flexDirection: 'row', flex: 1 }}>
                          {[,...Array(5)].map((x, index) => (
                            <Icon name="star" style={{ fontSize: 20 }} key={index}/>
                          ))}
                        </View>
                      </View>
                    </View>
                    <View>
                      <Button primary block onPress={() => navigate('TaskForm')}>
                        <Text>Join</Text>
                      </Button>
                    </View>
                  </View>
                </View>
              </Body>
            </CardItem>
          </Card>
        )} />
      </Content>
    )
  }
}
<|endoftext|>


<commit_before>/**
 * JavaScript implementation of the core concept 'object'
 * version: 0.2.2
 * (c) Liangcun Jiang
 * latest change: Feb 28, 2017.
 */
define(["dojo/_base/declare",
    "dojo/Deferred",
    "esri/tasks/query",
    "esri/layers/FeatureLayer",
    "esri/tasks/BufferParameters",
    "esri/tasks/RelationParameters",
    "esri/tasks/GeometryService"
], function (declare, Deferred, Query, FeatureLayer, BufferParameters, RelationParameters, GeometryService) {
    return declare(null, {
        /**
         * CcObject constructor: Constructs an object instance from either a Map Service or Feature Service
         * @param url: URL to the ArcGIS Server REST resource that represents an feature service.
         */
        constructor: function (url) {
            if (url === null || url === "" || url === undefined) {
                alert("Please enter a valid URL for the field data");
                return;
            }
            var featureLayer = new FeatureLayer(url);
            this.layer = featureLayer; //return featureLayer instead?
            console.log("A CcObject instance was created.");
        },

        /**
         * CcObject function: gets CcObject's bounds in form of a bounding box(xmin, ymin, xmax, ymax)
         * Return type: Deferred
         * Uses the callback function to receive the object's extent.
         */
        bounds: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryExtent(query);
            return process.then(function (extent) {
                return extent;
            });
        },

        /**
         * CcObject function: gets CcObject's geometry (can be Point, Curve, Surface, or GeometryCollection)
         * Return type: Deferred
         * Uses the callback function to receive the object's geometry.
         */
        getGeometry: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryFeatures(query);
            return process.then(function (featureSet) {
                //Subclasses of Geometry in ArcGIS JavaScript API: Extent, Multipoint, Point, Polygon, and Polyline.
                var geometry;
                switch (featureSet.geometryType) {
                    case "esriGeometryPolygon":
                        //A collection of rings ordered by their containment relationship.
                        //This may refer to Polygon or MultiPolygon in OGC terms
                        geometry = featureSet.features[0].geometry;
                        for (var i = 1; i < featureSet.features.length; i++) {
                            var rings = featureSet.features[i].geometry.rings;
                            for (var r = 0; r < rings.length; r++) {
                                geometry.addRing(rings[r]);
                            }
                        }
                        break;
                    case "esriGeometryPolyline":
                        //An ordered collection of paths.
                        //This may refer to LineRing or MultiLineRing in OGC terms
                        geometry = featureSet.features[0].geometry;
                        for (var i = 1; i < featureSet.features.length; i++) {
                            var paths = featureSet.features[i].geometry.paths;
                            for (var p = 0; p < paths.length; p++) {
                                geometry.addPath(paths[p]);
                            }
                        }
                        break;
                    //case "esriGeometryRing":
                    //    //An area bounded by one closed path.
                    //    break;
                    //case "esriGeometryPath":
                    //    //A connected sequence of segments.
                    //    break;
                    //case "esriGeometryLine":
                    //    //A straight line segment between two points.
                    //    break;
                    case "esriGeometryMultipoint":
                        //An ordered collection of points.
                        break;
                    case "esriGeometryPoint":
                        break;
                    case "esriGeometryEnvelope":
                        //A rectangle indicating the spatial extent of another geometry.
                        break;
                    default:
                        console.log("This FeatureSet does not contain geometry");
                        return;
                }
                console.log("geometry returned");
                return geometry;
            });
        },

        /**
         * CcObject function: Creates buffer polygons at a specified distance around the given object.
         * @param distance: the distance the input object are buffered.
         * @param unitType: the unit for calculating each buffer distance.(case insensitive: kilometer = Kilometer)
         *                 Units can be singular or plural forms: e.g. Foot = feet
         * Return type: Deferred
         * Uses the callback function to receive an array of Geometry that contains the buffer polygons.
         */
        buffer: function (distance, unitType) {
            //This service provided by ESRI is for development and testing purposes only.
            //var gsUrl = "https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);

            //Defines valid unit types here
            var bufferUnits = {
                "METER": GeometryService.UNIT_METER,
                "METERS": GeometryService.UNIT_METER,
                "KILOMETER": GeometryService.UNIT_KILOMETER,
                "KILOMETERS": GeometryService.UNIT_KILOMETER,
                "FOOT": GeometryService.UNIT_FOOT, //International foot (0.3048 meters)
                "FEET": GeometryService.UNIT_FOOT,
                "MILE": GeometryService.UNIT_STATUTE_MILE, //Miles (5,280 feet, 1,760 yards, or exactly 1,609.344 meters)
                "MILES": GeometryService.UNIT_STATUTE_MILE,
                "NAUTICAL_MILE": GeometryService.UNIT_NAUTICAL_MILE, //Nautical Miles (1,852 meters)
                "NAUTICAL_MILES": GeometryService.UNIT_NAUTICAL_MILE,
                "DEGREE": GeometryService.UNIT_DEGREE,
                "DEGREES": GeometryService.UNIT_DEGREE
            };

            //setup the buffer parameters
            var params = new BufferParameters();
            params.distances = [distance];
            params.unit = bufferUnits[unitType.toUpperCase()];
            //If true, all geometries buffered at a given distance are unioned into
            //a single (possibly multipart) polygon, and the unioned geometry is placed in the output array.
            params.unionResults = true;

            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryFeatures(query).then(function (featureSet) {
                var geometryArray = [];
                for (var i = 0; i < featureSet.features.length; i++) {
                    geometryArray.push(featureSet.features[i].geometry);
                }
                return geometryArray;
            });
            //Get <Geometry[]> geometries of the CcObject and do the buffer
            return process.then(function (geoArray) {
                //The Geometry Service allows a maxBufferCount of 12500.
                // The maxBufferCount property establishes the maximum number of features that can be buffered
                if (geoArray.length <= 12500) {
                    params.geometries = geoArray;
                    //do the buffer
                    console.log("Doing the buffer...");
                    //buffer function returns a "<Polygon[]> geometries" Array[1]
                    return gs.buffer(params);
                } else {
                    //if the number of features exceeds the maxBufferCount, then executes buffer operation in two parts.
                    //Needs to extend this code snippet if the number of features > 250000.
                    params.geometries = geoArray.slice(0, 12500)
                    //do the buffer
                    console.log("Buffering part 1...");
                    return gs.buffer(params).then(function (bufferedGeometries1) {
                        console.log("Buffering part 2...");
                        params.geometries = geoArray.slice(12500);
                        var gs2 = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
                        return gs2.buffer(params).then(function (bufferedGeometries2) {
                            //console.log([bufferedGeometries1, bufferedGeometries2]);
                            //console.log(bufferedGeometries1.concat(bufferedGeometries2));
                            var gs3 = new GeometryService(gsUrl);
                            //constructs the set-theoretic union of the two buffered geometries
                            console.log("Unifying two parts...");
                            //union function returns a "<Geometry> geometry" Object, then converts it to an Array[1]
                            return gs3.union(bufferedGeometries1.concat(bufferedGeometries2)).then(function (geoUnion) {
                                console.log("buffer finished!");
                                return [geoUnion];
                            });
                        });
                    });
                }
            });
        },

        /**
         * CcObject function: returns true if self and obj are in a relationship of type relType.
         * @param obj:
         * @param relType: The spatial relationship to be tested between the two CcObject.
         * Return type: Deferred
         * Uses the callback function to receive the result.
         */
        relation: function (obj, relType) {
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);
            var relationParams = new RelationParameters();
            relationParams.geometries1 = null;
            relationParams.geometries2 = null;
            relationParams.relation = RelationParameters.SPATIAL_REL_WITHIN;
            return gs.relation(relationParams).then(function (relatedResults) {
                return relatedResults ? true : false;
            });
        },

        /**
         * CcObject function: returns value of property in obj
         * @param prop: the property name
         * Return type: Deferred
         * Uses the callback function to receive the result.
         */
        property: function (prop) {

        }
    });
});<commit_msg>a slight change<commit_after>/**
 * JavaScript implementation of the core concept 'object'
 * version: 0.2.3
 * (c) Liangcun Jiang
 * latest change: March 16, 2017.
 */
define(["dojo/_base/declare",
    "esri/tasks/query",
    "esri/layers/FeatureLayer",
    "esri/tasks/BufferParameters",
    "esri/tasks/RelationParameters",
    "esri/tasks/GeometryService"
], function (declare, Query, FeatureLayer, BufferParameters, RelationParameters, GeometryService) {
    return declare(null, {
        /**
         * CcObject constructor: Constructs an object instance from either a Map Service or Feature Service
         * @param url: URL to the ArcGIS Server REST resource that represents an feature service.
         */
        constructor: function (url) {
            if (url === null || url === "" || url === undefined) {
                alert("Please enter a valid URL for the field data");
                return;
            }
            var featureLayer = new FeatureLayer(url);
            this.layer = featureLayer; //return featureLayer instead?
            console.log("A CcObject instance was created.");
        },

        /**
         * CcObject function: gets CcObject's bounds in form of a bounding box(xmin, ymin, xmax, ymax)
         * Return type: Deferred
         * Uses the callback function to receive the object's extent.
         */
        bounds: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryExtent(query);
            return process.then(function (extent) {
                return extent;
            });
        },

        /**
         * CcObject function: gets CcObject's geometry (can be Point, Curve, Surface, or GeometryCollection)
         * Return type: Deferred
         * Uses the callback function to receive the object's geometry.
         */
        getGeometry: function () {
            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryFeatures(query);
            return process.then(function (featureSet) {
                //Subclasses of Geometry in ArcGIS JavaScript API: Extent, Multipoint, Point, Polygon, and Polyline.
                var geometry;
                switch (featureSet.geometryType) {
                    case "esriGeometryPolygon":
                        //A collection of rings ordered by their containment relationship.
                        //This may refer to Polygon or MultiPolygon in OGC terms
                        geometry = featureSet.features[0].geometry;
                        for (var i = 1; i < featureSet.features.length; i++) {
                            var rings = featureSet.features[i].geometry.rings;
                            for (var r = 0; r < rings.length; r++) {
                                geometry.addRing(rings[r]);
                            }
                        }
                        break;
                    case "esriGeometryPolyline":
                        //An ordered collection of paths.
                        //This may refer to LineRing or MultiLineRing in OGC terms
                        geometry = featureSet.features[0].geometry;
                        for (var i = 1; i < featureSet.features.length; i++) {
                            var paths = featureSet.features[i].geometry.paths;
                            for (var p = 0; p < paths.length; p++) {
                                geometry.addPath(paths[p]);
                            }
                        }
                        break;
                    //case "esriGeometryRing":
                    //    //An area bounded by one closed path.
                    //    break;
                    //case "esriGeometryPath":
                    //    //A connected sequence of segments.
                    //    break;
                    //case "esriGeometryLine":
                    //    //A straight line segment between two points.
                    //    break;
                    case "esriGeometryMultipoint":
                        //An ordered collection of points.
                        break;
                    case "esriGeometryPoint":
                        break;
                    case "esriGeometryEnvelope":
                        //A rectangle indicating the spatial extent of another geometry.
                        break;
                    default:
                        console.log("This FeatureSet does not contain geometry");
                        return;
                }
                console.log("geometry returned");
                return geometry;
            });
        },

        /**
         * CcObject function: Creates buffer polygons at a specified distance around the given object.
         * @param distance: the distance the input object are buffered.
         * @param unitType: the unit for calculating each buffer distance.(case insensitive: kilometer = Kilometer)
         *                 Units can be singular or plural forms: e.g. Foot = feet
         * Return type: Deferred
         * Uses the callback function to receive an array of Geometry that contains the buffer polygons.
         */
        buffer: function (distance, unitType) {
            //This service provided by ESRI is for development and testing purposes only.
            //var gsUrl = "https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer";
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);

            //Defines valid unit types here
            var bufferUnits = {
                "METER": GeometryService.UNIT_METER,
                "METERS": GeometryService.UNIT_METER,
                "KILOMETER": GeometryService.UNIT_KILOMETER,
                "KILOMETERS": GeometryService.UNIT_KILOMETER,
                "FOOT": GeometryService.UNIT_FOOT, //International foot (0.3048 meters)
                "FEET": GeometryService.UNIT_FOOT,
                "MILE": GeometryService.UNIT_STATUTE_MILE, //Miles (5,280 feet, 1,760 yards, or exactly 1,609.344 meters)
                "MILES": GeometryService.UNIT_STATUTE_MILE,
                "NAUTICAL_MILE": GeometryService.UNIT_NAUTICAL_MILE, //Nautical Miles (1,852 meters)
                "NAUTICAL_MILES": GeometryService.UNIT_NAUTICAL_MILE,
                "DEGREE": GeometryService.UNIT_DEGREE,
                "DEGREES": GeometryService.UNIT_DEGREE
            };

            //setup the buffer parameters
            var params = new BufferParameters();
            params.distances = [distance];
            params.unit = bufferUnits[unitType.toUpperCase()];
            //If true, all geometries buffered at a given distance are unioned into
            //a single (possibly multipart) polygon, and the unioned geometry is placed in the output array.
            params.unionResults = true;

            var query = new Query();
            query.where = "1=1"; // Query for all records
            query.outFields = ["*"];
            query.returnGeometry = true;
            var process = this.layer.queryFeatures(query).then(function (featureSet) {
                var geometryArray = [];
                for (var i = 0; i < featureSet.features.length; i++) {
                    geometryArray.push(featureSet.features[i].geometry);
                }
                return geometryArray;
            });
            //Get <Geometry[]> geometries of the CcObject and do the buffer
            return process.then(function (geoArray) {
                //The Geometry Service allows a maxBufferCount of 12500.
                // The maxBufferCount property establishes the maximum number of features that can be buffered
                if (geoArray.length <= 12500) {
                    params.geometries = geoArray;
                    //do the buffer
                    console.log("Doing the buffer...");
                    //buffer function returns a "<Polygon[]> geometries" Array[1]
                    return gs.buffer(params);
                } else {
                    //if the number of features exceeds the maxBufferCount, then executes buffer operation in two parts.
                    //Needs to extend this code snippet if the number of features > 250000.
                    params.geometries = geoArray.slice(0, 12500)
                    //do the buffer
                    console.log("Buffering part 1...");
                    return gs.buffer(params).then(function (bufferedGeometries1) {
                        console.log("Buffering part 2...");
                        params.geometries = geoArray.slice(12500);
                        var gs2 = new GeometryService("https://utility.arcgisonline.com/ArcGIS/rest/services/Geometry/GeometryServer");
                        return gs2.buffer(params).then(function (bufferedGeometries2) {
                            //console.log([bufferedGeometries1, bufferedGeometries2]);
                            //console.log(bufferedGeometries1.concat(bufferedGeometries2));
                            var gs3 = new GeometryService(gsUrl);
                            //constructs the set-theoretic union of the two buffered geometries
                            console.log("Unifying two parts...");
                            //union function returns a "<Geometry> geometry" Object, then converts it to an Array[1]
                            return gs3.union(bufferedGeometries1.concat(bufferedGeometries2)).then(function (geoUnion) {
                                console.log("buffer finished!");
                                return [geoUnion];
                            });
                        });
                    });
                }
            });
        },

        /**
         * CcObject function: returns true if self and obj are in a relationship of type relType.
         * @param obj:
         * @param relType: The spatial relationship to be tested between the two CcObject.
         * Return type: Deferred
         * Uses the callback function to receive the result.
         */
        relation: function (obj, relType) {
            var gsUrl = "https://ags-raid.geog.ucsb.edu:6443/arcgis/rest/services/Utilities/Geometry/GeometryServer";
            var gs = new GeometryService(gsUrl);
            var relationParams = new RelationParameters();
            relationParams.geometries1 = null;
            relationParams.geometries2 = null;
            relationParams.relation = RelationParameters.SPATIAL_REL_WITHIN;
            return gs.relation(relationParams).then(function (relatedResults) {
                return relatedResults ? true : false;
            });
        },

        /**
         * CcObject function: returns value of property in obj
         * @param prop: the property name
         * Return type: Deferred
         * Uses the callback function to receive the result.
         */
        property: function (prop) {

        }
    });
});<|endoftext|>


<commit_before>// aiming logic
var Aiming = (function () {
    var HINDSIGHT_RADIUS = 21,
        HINDSIGHT_IMAGE_SCALE = 0.08,
        HINDSIGHT_IMAGE_OFFSET = 250,
        POWERSLIDER_HEIGHT = 5,
        hindsightBackground,
        hindsight,
        powerBar = new Kinetic.Rect({
            stroke: 'black',
            fillLinearGradientColorStops: [0, 'red', 0.5, 'rgb(37,204,4)', 1, 'yellow']
        }),
        powerSlider = new Kinetic.Rect({
            fill: 'black',
            stroke: 'black'
        });

    hindsight = new Kinetic.Circle({
        x: 0,
        y: 0,
        radius: HINDSIGHT_RADIUS
    });

    // making hindsight bakcground
    hindsightBackground = new Image();
    hindsightBackground.src = 'images/olive.png';
    hindsightBackground.onload = function () {
        hindsight.setFillPatternImage(hindsightBackground);
        hindsight.fillPatternScale({
            x: HINDSIGHT_IMAGE_SCALE,
            y: HINDSIGHT_IMAGE_SCALE
        });

        hindsight.fillPatternOffset({
            x: HINDSIGHT_IMAGE_OFFSET,
            y: HINDSIGHT_IMAGE_OFFSET
        });
    };

    function calculateHitPoint() {
        var hitPointX = hindsight.getX(),
            power = stage.height() / 2 - powerSlider.getY(),
            hitPointY = hindsight.getY() - power;

        return { x: hitPointX, y: hitPointY };
    }

    return {
        initialize: function initialize() {

            powerBar.x(stage.getWidth() * 67 / 100);
            powerBar.y(stage.getHeight() * 20 / 100);
            powerBar.width(stage.getWidth() * 4 / 100);
            powerBar.height(stage.getHeight() * 60 / 100);
            powerBar.fillLinearGradientStartPoint({ x: 0, y: 0 });
            powerBar.fillLinearGradientEndPoint({ x: 0, y: stage.getHeight() * 60 / 100 });

            powerSlider.x(powerBar.getX() - 5);
            powerSlider.y(stage.height() / 2);
            powerSlider.width(powerBar.width() + 10);
            powerSlider.height(POWERSLIDER_HEIGHT);

            secondLayer.clear();
            secondLayer.add(hindsight);
            secondLayer.add(powerBar);
            secondLayer.add(powerSlider);

            hindsight.opacity(1);

            return Q();
        },
        // This function animates hindsight movement around the target and stops it on keypress
        setAngle: function setAngle() {
            var ORBIT_RADIUS = TARGET_RADIUS + 38,
                HINDSIGHT_MOVING_SPEED = 50,
                deferred = Q.defer(),
                angle = 0, // The start angle with which the ball is going to change it's position
                isSpacePressed = false;

            function calculateXForMovingTheBallInTheOrbit() {
                return TARGET_CENTER_X + ORBIT_RADIUS * Math.cos(angle);
            }

            function calculateYForMovingTheBallInTheOrbit() {
                return TARGET_CENTER_Y + ORBIT_RADIUS * Math.sin(angle);
            }

            function animation() {
                if (isSpacePressed) {
                    deferred.resolve();
                    return;
                }
                else {
                    hindsight.setX(calculateXForMovingTheBallInTheOrbit());
                    hindsight.setY(calculateYForMovingTheBallInTheOrbit());

                    // Updating the angle to change the position of the ball on the orbit
                    angle += Math.PI / HINDSIGHT_MOVING_SPEED;

                    secondLayer.draw();
                }

                requestAnimationFrame(animation);
            }

            window.addEventListener("keydown", function (event) {
                if (event.keyCode === 32) {
                    isSpacePressed = true;
                }
            });

            $('#container').on('click', function(){
                isSpacePressed = true;
            });

            // document.addEventListener("click", function (event) {
            //     isSpacePressed = true;
            // });

            animation();
            return deferred.promise;
        },
        // This function animates power bar movement and stops it on keypress
        setPower: function setPower() {
            var POWERSLIDER_MOVING_SPEED = 0.03,
                deferred = Q.defer(),
                powerBarTop = powerBar.getY(),
                powerBarBottom = powerBar.getY() + powerBar.height(),
                isSpacePressed = false,
                direction = -1;

            function calculateYForMovingThePowerSlider() {
                var hasPowerSliderReachedPowerBarEnd =
                    ((powerSlider.getY() <= powerBarTop) || (powerSlider.getY() >= powerBarBottom));

                if (hasPowerSliderReachedPowerBarEnd) {
                    // change moving direction
                    direction *= -1;
                }

                return powerSlider.getY() + ((powerBarTop - powerBarBottom) * POWERSLIDER_MOVING_SPEED) * direction;
            }

            function animation() {
                if (isSpacePressed) {
                    // aiming is done and returns target coordinates
                    var hitPoint = calculateHitPoint();
                    // remove olive
                    hindsight.opacity(0);
                    deferred.resolve(hitPoint);
                    return;
                }
                else {
                    powerSlider.setY(calculateYForMovingThePowerSlider());
                }

                secondLayer.draw();
                requestAnimationFrame(animation);
            }

            window.addEventListener("keydown", function (event) {
                if (event.keyCode === 32) {
                    isSpacePressed = true;
                }
            });

            $('#container').on('click', function(){
                isSpacePressed = true;
            });

            // window.addEventListener("click", function (event) {
            //     isSpacePressed = true;
            // });

            animation();
            return deferred.promise;
        },
        // This function animates hindsight movement across the target and stops it on keypress
        setPosition: function setPosition() {
            var HINDSIGHT_MOVING_SPEED = 0.03,
                deferred = Q.defer(),
                startPointX = hindsight.getX(),
                startPointY = hindsight.getY(),
                endPointX = TARGET_CENTER_X * 2 - startPointX,
                endPointY = TARGET_CENTER_Y * 2 - startPointY,
                isSpacePressed = false;

            secondLayer.add(hindsight);

            // moving logic
            function calculateXForMovingTheHindsightOnTheLine() {
                var hindsightDistanceFromStartingPoint =
                    Math.sqrt(
                        Math.pow(hindsight.getX() - startPointX, 2)
                        + Math.pow(hindsight.getY() - startPointY, 2));

                // if hindsight gets to the end change direction
                if (hindsightDistanceFromStartingPoint >= 2 * (TARGET_RADIUS + 20)) {
                    var bufferX = startPointX,
                        bufferY = startPointY;
                    startPointX = endPointX;
                    startPointY = endPointY;
                    endPointX = bufferX;
                    endPointY = bufferY;
                }

                return hindsight.getX() + (endPointX - startPointX) * HINDSIGHT_MOVING_SPEED;
            }

            function calculateYForMovingTheHindsightOnTheLine() {
                return hindsight.getY() + (endPointY - startPointY) * HINDSIGHT_MOVING_SPEED;
            }

            function animation() {
                if (isSpacePressed) {
                    deferred.resolve();
                    return;
                }
                else {
                    hindsight.setX(calculateXForMovingTheHindsightOnTheLine());
                    hindsight.setY(calculateYForMovingTheHindsightOnTheLine());
                }

                secondLayer.draw();
                requestAnimationFrame(animation);
            }

            window.addEventListener("keydown", function (event) {
                if (event.keyCode === 32) {
                    isSpacePressed = true;
                }
            });

            // window.addEventListener("click", function (event) {
            //     isSpacePressed = true;
            // });

            $('#container').on('click', function(){
                isSpacePressed = true;
            });

            animation();
            return deferred.promise;
        }
    }
} ());<commit_msg>Revert "second try to fix mobile support"<commit_after>// aiming logic
var Aiming = (function () {
    var HINDSIGHT_RADIUS = 21,
        HINDSIGHT_IMAGE_SCALE = 0.08,
        HINDSIGHT_IMAGE_OFFSET = 250,
        POWERSLIDER_HEIGHT = 5,
        hindsightBackground,
        hindsight,
        powerBar = new Kinetic.Rect({
            stroke: 'black',
            fillLinearGradientColorStops: [0, 'red', 0.5, 'rgb(37,204,4)', 1, 'yellow']
        }),
        powerSlider = new Kinetic.Rect({
            fill: 'black',
            stroke: 'black'
        });

    hindsight = new Kinetic.Circle({
        x: 0,
        y: 0,
        radius: HINDSIGHT_RADIUS
    });

    // making hindsight bakcground
    hindsightBackground = new Image();
    hindsightBackground.src = 'images/olive.png';
    hindsightBackground.onload = function () {
        hindsight.setFillPatternImage(hindsightBackground);
        hindsight.fillPatternScale({
            x: HINDSIGHT_IMAGE_SCALE,
            y: HINDSIGHT_IMAGE_SCALE
        });

        hindsight.fillPatternOffset({
            x: HINDSIGHT_IMAGE_OFFSET,
            y: HINDSIGHT_IMAGE_OFFSET
        });
    };

    function calculateHitPoint() {
        var hitPointX = hindsight.getX(),
            power = stage.height() / 2 - powerSlider.getY(),
            hitPointY = hindsight.getY() - power;

        return { x: hitPointX, y: hitPointY };
    }

    return {
        initialize: function initialize() {

            powerBar.x(stage.getWidth() * 67 / 100);
            powerBar.y(stage.getHeight() * 20 / 100);
            powerBar.width(stage.getWidth() * 4 / 100);
            powerBar.height(stage.getHeight() * 60 / 100);
            powerBar.fillLinearGradientStartPoint({ x: 0, y: 0 });
            powerBar.fillLinearGradientEndPoint({ x: 0, y: stage.getHeight() * 60 / 100 });

            powerSlider.x(powerBar.getX() - 5);
            powerSlider.y(stage.height() / 2);
            powerSlider.width(powerBar.width() + 10);
            powerSlider.height(POWERSLIDER_HEIGHT);

            secondLayer.clear();
            secondLayer.add(hindsight);
            secondLayer.add(powerBar);
            secondLayer.add(powerSlider);

            hindsight.opacity(1);

            return Q();
        },
        // This function animates hindsight movement around the target and stops it on keypress
        setAngle: function setAngle() {
            var ORBIT_RADIUS = TARGET_RADIUS + 38,
                HINDSIGHT_MOVING_SPEED = 50,
                deferred = Q.defer(),
                angle = 0, // The start angle with which the ball is going to change it's position
                isSpacePressed = false;

            function calculateXForMovingTheBallInTheOrbit() {
                return TARGET_CENTER_X + ORBIT_RADIUS * Math.cos(angle);
            }

            function calculateYForMovingTheBallInTheOrbit() {
                return TARGET_CENTER_Y + ORBIT_RADIUS * Math.sin(angle);
            }

            function animation() {
                if (isSpacePressed) {
                    deferred.resolve();
                    return;
                }
                else {
                    hindsight.setX(calculateXForMovingTheBallInTheOrbit());
                    hindsight.setY(calculateYForMovingTheBallInTheOrbit());

                    // Updating the angle to change the position of the ball on the orbit
                    angle += Math.PI / HINDSIGHT_MOVING_SPEED;

                    secondLayer.draw();
                }

                requestAnimationFrame(animation);
            }

            window.addEventListener("keydown", function (event) {
                if (event.keyCode === 32) {
                    isSpacePressed = true;
                }
            });

            document.addEventListener("click", function (event) {
                isSpacePressed = true;
            });

            animation();
            return deferred.promise;
        },
        // This function animates power bar movement and stops it on keypress
        setPower: function setPower() {
            var POWERSLIDER_MOVING_SPEED = 0.03,
                deferred = Q.defer(),
                powerBarTop = powerBar.getY(),
                powerBarBottom = powerBar.getY() + powerBar.height(),
                isSpacePressed = false,
                direction = -1;

            function calculateYForMovingThePowerSlider() {
                var hasPowerSliderReachedPowerBarEnd =
                    ((powerSlider.getY() <= powerBarTop) || (powerSlider.getY() >= powerBarBottom));

                if (hasPowerSliderReachedPowerBarEnd) {
                    // change moving direction
                    direction *= -1;
                }

                return powerSlider.getY() + ((powerBarTop - powerBarBottom) * POWERSLIDER_MOVING_SPEED) * direction;
            }

            function animation() {
                if (isSpacePressed) {
                    // aiming is done and returns target coordinates
                    var hitPoint = calculateHitPoint();
                    // remove olive
                    hindsight.opacity(0);
                    deferred.resolve(hitPoint);
                    return;
                }
                else {
                    powerSlider.setY(calculateYForMovingThePowerSlider());
                }

                secondLayer.draw();
                requestAnimationFrame(animation);
            }

            window.addEventListener("keydown", function (event) {
                if (event.keyCode === 32) {
                    isSpacePressed = true;
                }
            });

            window.addEventListener("click", function (event) {
                isSpacePressed = true;
            });

            animation();
            return deferred.promise;
        },
        // This function animates hindsight movement across the target and stops it on keypress
        setPosition: function setPosition() {
            var HINDSIGHT_MOVING_SPEED = 0.03,
                deferred = Q.defer(),
                startPointX = hindsight.getX(),
                startPointY = hindsight.getY(),
                endPointX = TARGET_CENTER_X * 2 - startPointX,
                endPointY = TARGET_CENTER_Y * 2 - startPointY,
                isSpacePressed = false;

            secondLayer.add(hindsight);

            // moving logic
            function calculateXForMovingTheHindsightOnTheLine() {
                var hindsightDistanceFromStartingPoint =
                    Math.sqrt(
                        Math.pow(hindsight.getX() - startPointX, 2)
                        + Math.pow(hindsight.getY() - startPointY, 2));

                // if hindsight gets to the end change direction
                if (hindsightDistanceFromStartingPoint >= 2 * (TARGET_RADIUS + 20)) {
                    var bufferX = startPointX,
                        bufferY = startPointY;
                    startPointX = endPointX;
                    startPointY = endPointY;
                    endPointX = bufferX;
                    endPointY = bufferY;
                }

                return hindsight.getX() + (endPointX - startPointX) * HINDSIGHT_MOVING_SPEED;
            }

            function calculateYForMovingTheHindsightOnTheLine() {
                return hindsight.getY() + (endPointY - startPointY) * HINDSIGHT_MOVING_SPEED;
            }

            function animation() {
                if (isSpacePressed) {
                    deferred.resolve();
                    return;
                }
                else {
                    hindsight.setX(calculateXForMovingTheHindsightOnTheLine());
                    hindsight.setY(calculateYForMovingTheHindsightOnTheLine());
                }

                secondLayer.draw();
                requestAnimationFrame(animation);
            }

            window.addEventListener("keydown", function (event) {
                if (event.keyCode === 32) {
                    isSpacePressed = true;
                }
            });

            window.addEventListener("click", function (event) {
                isSpacePressed = true;
            });

            animation();
            return deferred.promise;
        }
    }
} ());<|endoftext|>


<commit_before>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { format } from 'd3-format';

import './widget-chart-tooltip-styles.scss';

class WidgetChartTooltip extends PureComponent {
  render() {
    const { payload, settings, colors, hideZeros } = this.props;
    const values = payload.length > 0 && payload[0].payload;

    return (

        {settings.map(
          d =>
            (hideZeros && !values[d.key] ? null : (

                {d.label && (

                    {colors &&
                      colors[d.key] && (

                      )}
                    {{values[d.label]}}

                )}
                {d.unit
                  ? format(
                    d.unit === '%'
                      ? d.unitFormat ? d.unitFormat : '.1f'
                      : '.3s'
                  )(values[d.key])
                  : values[d.key]}
                {d.unit}

            ))
        )}

    );
  }
}

WidgetChartTooltip.propTypes = {
  payload: PropTypes.array,
  settings: PropTypes.array,
  colors: PropTypes.object,
  hideZeros: PropTypes.bool
};

export default WidgetChartTooltip;
<commit_msg>improve char tooltip<commit_after>import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { format } from 'd3-format';

import './widget-chart-tooltip-styles.scss';

class WidgetChartTooltip extends PureComponent {
  render() {
    const { payload, settings, colors, hideZeros } = this.props;
    const values = payload.length > 0 && payload[0].payload;

    return (

        {settings.map(
          d =>
            (hideZeros && !values[d.key] ? null : (

                {d.label && (

                    {colors &&
                      colors[d.key] && (

                      )}
                    {{values[d.label]}}

                )}
                {d.unit
                  ? format(
                    d.unitFormat
                      ? d.unitFormat
                      : d.unit === '%'
                        ? '.1f'
                        : '.3s'
                  )(values[d.key])
                  : values[d.key]}
                {d.unit}

            ))
        )}

    );
  }
}

WidgetChartTooltip.propTypes = {
  payload: PropTypes.array,
  settings: PropTypes.array,
  colors: PropTypes.object,
  hideZeros: PropTypes.bool
};

export default WidgetChartTooltip;
<|endoftext|>