<commit_before>/* 
 * EVENT REGISTRATION
 *
 * This page will be used by users to register for events in a 
 * specific selected competition
 */

import style from "./style.css"
import React from 'react'
import AddEvent from './PageEventRegistration/addEvent.jsx'
import EventTable from './common/EventTable.jsx'
import Autocomplete from 'react-autocomplete'
import Page from './Page.jsx'
import { RadioGroup, RadioButton } from 'react-toolbox/lib/radio';
import {Button, IconButton} from 'react-toolbox/lib/button';
import Box from './common/Box.jsx'
import { Link } from 'react-router'
import cloneDeep from 'lodash/cloneDeep';
import findIndex from 'lodash/findIndex';

// competition/:competition_id/eventregistration
export default class PageEventRegistration extends React.Component {


  constructor(props) {
    super(props)
    this.state = {
      /** We will populate this w/ data from the API */
      competition: null,
      competition_events: [],
      user_competition_events: [],
      competitors: [],
      levels: [],
      level_styles: [],
      level_style_events: [],

      value: '',
      loading: false,
      partner: null,

      // Selected stuff
      levelid: null,
      styleid: null,
      eventid: null,
      isLeading: null,
    }

    /** Take the competition ID from the URL (Router hands
    it to us; see the path for this Page on Router) and make
    sure it's an integer */
    try {
      // this.competition_id = this.props.selected.competition.id
      this.competition_id = this.props.params.competition_id
      this.competitor_id = this.props.profile.competitor_id 
    }
    catch (e) { alert('Invalid competition ID!') }
  }
  componentDidMount(){
    /* Call the API for competition data */
    this.props.api.get(`/api/competition/${this.competition_id}`)
      .then(json => { 
        // update the state of our component
        this.setState({ competition : json })
      })
      // todo; display a nice (sorry, there's no connection!) error
      // and setup a timer to retry. Fingers crossed, hopefully the 
      // connection comes back
      .catch(err => alert(err))

    /** Pretty similar to above! */
    this.props.api.get(`/api/competition/${this.competition_id}/events`)
      .then(json => {
        this.setState({ competition_events : json})
      })
      .catch(err => alert(err))

    this.props.api.get(`/api/competitors/${this.competitor_id}/${this.competition_id}/events`)
      .then(json => {
        console.log(json)
        for (let i = 0; i < json.length; i++) {
            json[i].title = json[i].dance;
            if (json[i].leadcompetitorid == this.competitor_id) {
                json[i].leader = "You"
                json[i].follower = json[i].followfirstname+" "+json[i].followlastname
            } else {
                json[i].follower = "You"
                json[i].leader = json[i].leadfirstname+" "+json[i].leadlastname
            }
        }
        this.setState({user_competition_events: json})
      })
      .catch(err => { alert(err); console.log(err)})

    /** Fetch levels in a competition */
    this.props.api.get(`/api/competition/${this.competition_id}/levels`)
      .then(json => {

        this.setState({levels: json})
      })
      .catch(err => alert(err))

    /** Fetch competitors for partner search */
    this.props.api.get(`/api/competitors`)
      .then(json => {
        json = json.filter(item => {
          return item.id != this.competitor_id
        })
        this.setState({competitors: json})
      })
      .catch(err => alert(err))
  }

  handleLevelChange = (levelid) => {
    fetch(`/api/competition/${this.competition_id}/level/${levelid}/styles`)
      .then(response => {
        return response.json()
      })
      .then(json => {
        this.setState({level_styles: json})
      })
      .catch(err => alert(err))
    this.setState({
        levelid: parseInt(levelid),
        eventid: null 
    });
  };

  handleStyleChange = (styleid) => {
    fetch(`/api/competition/${this.competition_id}/level/${this.state.levelid}/style/${styleid}`)
      .then(response => {
        return response.json()
      })
      .then(json => {
        this.setState({level_style_events: json})
      })
      .catch(err => alert(err))
    this.setState({
        styleid: parseInt(styleid),
        eventid: null
    });
  };

  handleEventChange = (eventid) => {
    this.setState({
      eventid: parseInt(eventid)
    });
  };

  handleLeadChange = (isLeading) => {
      this.setState({isLeading});
  };

  checkIfNotExists = (reg) => {
      const { eventid } = this.state;
      return (reg["eventid"] != eventid);
  };

  registerEventHandler = () => {
      const { levelid, styleid, eventid, partner, isLeading, user_competition_events } = this.state;
      const button_enabled = (eventid != null) && (isLeading != null) && (partner != null)
      if (button_enabled) {
          if (!user_competition_events.every(this.checkIfNotExists)) {
              console.log(user_competition_events.every(this.checkIfNotExists));
              alert('You are already registered for this event!');
              return false
          } else if (this.competitor_id == partner) {
              alert('This is a partner dance competition silly, dance with somebody else!');
              return false
          }
          var leadcompetitorid = partner;
          var followcompetitorid = this.competitor_id;
          if (isLeading == 'Leading') {
            leadcompetitorid = this.competitor_id;
            followcompetitorid = partner;
          }
            fetch("/api/create_partnership", {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    leadcompetitorid: leadcompetitorid,
                    followcompetitorid: followcompetitorid,
                    eventid: eventid,
                    competitionid: this.competition_id
                })
            }).then((response) => {
                fetch("/api/create_paymentrecord", {<commit_msg>improve event selection<commit_after>/* 
 * EVENT REGISTRATION
 *
 * This page will be used by users to register for events in a 
 * specific selected competition
 */

import style from "./style.css"
import React from 'react'
import AddEvent from './PageEventRegistration/addEvent.jsx'
import EventTable from './common/EventTable.jsx'
import Autocomplete from 'react-autocomplete'
import Page from './Page.jsx'
import { RadioGroup, RadioButton } from 'react-toolbox/lib/radio';
import {Button, IconButton} from 'react-toolbox/lib/button';
import Box from './common/Box.jsx'
import { Link } from 'react-router'
import cloneDeep from 'lodash/cloneDeep';
import findIndex from 'lodash/findIndex';

// competition/:competition_id/eventregistration
export default class PageEventRegistration extends React.Component {


  constructor(props) {
    super(props)
    this.state = {
      /** We will populate this w/ data from the API */
      competition: null,
      competition_events: [],
      user_competition_events: [],
      competitors: [],
      levels: [],
      level_styles: [],
      level_style_events: [],

      value: '',
      loading: false,
      partner: null,

      // Selected stuff
      levelid: null,
      styleid: null,
      eventid: null,
      isLeading: null,
    }

    /** Take the competition ID from the URL (Router hands
    it to us; see the path for this Page on Router) and make
    sure it's an integer */
    try {
      // this.competition_id = this.props.selected.competition.id
      this.competition_id = this.props.params.competition_id
      this.competitor_id = this.props.profile.competitor_id 
    }
    catch (e) { alert('Invalid competition ID!') }
  }
  componentDidMount(){
    /* Call the API for competition data */
    this.props.api.get(`/api/competition/${this.competition_id}`)
      .then(json => { 
        // update the state of our component
        this.setState({ competition : json })
      })
      // todo; display a nice (sorry, there's no connection!) error
      // and setup a timer to retry. Fingers crossed, hopefully the 
      // connection comes back
      .catch(err => alert(err))

    /** Pretty similar to above! */
    this.props.api.get(`/api/competition/${this.competition_id}/events`)
      .then(json => {
        this.setState({ competition_events : json})
      })
      .catch(err => alert(err))

    this.props.api.get(`/api/competitors/${this.competitor_id}/${this.competition_id}/events`)
      .then(json => {
        console.log(json)
        for (let i = 0; i < json.length; i++) {
            json[i].title = json[i].dance;
            if (json[i].leadcompetitorid == this.competitor_id) {
                json[i].leader = "You"
                json[i].follower = json[i].followfirstname+" "+json[i].followlastname
            } else {
                json[i].follower = "You"
                json[i].leader = json[i].leadfirstname+" "+json[i].leadlastname
            }
        }
        this.setState({user_competition_events: json})
      })
      .catch(err => { alert(err); console.log(err)})

    /** Fetch levels in a competition */
    this.props.api.get(`/api/competition/${this.competition_id}/levels`)
      .then(json => {

        this.setState({levels: json})
      })
      .catch(err => alert(err))

    /** Fetch competitors for partner search */
    this.props.api.get(`/api/competitors`)
      .then(json => {
        json = json.filter(item => {
          return item.id != this.competitor_id
        })
        this.setState({competitors: json})
      })
      .catch(err => alert(err))
  }

  handleLevelChange = (levelid) => {
    fetch(`/api/competition/${this.competition_id}/level/${levelid}/styles`)
      .then(response => {
        return response.json()
      })
      .then(json => {
        this.setState({level_styles: json})
      })
      .catch(err => alert(err))
      if ( this.state.styleid){
        fetch(`/api/competition/${this.competition_id}/level/${levelid}/style/${this.state.styleid}`)
        .then(response => {
          return response.json()
        })
        .then(json => {
          this.setState({level_style_events: json})
        })
        .catch(err => alert(err))
      }
      this.setState({
          levelid: parseInt(levelid),
          eventid: null 
      });
  };

  handleStyleChange = (styleid) => {
    fetch(`/api/competition/${this.competition_id}/level/${this.state.levelid}/style/${styleid}`)
      .then(response => {
        return response.json()
      })
      .then(json => {
        this.setState({level_style_events: json})
      })
      .catch(err => alert(err))
    this.setState({
        styleid: parseInt(styleid),
        eventid: null
    });
  };

  handleEventChange = (eventid) => {
    this.setState({
      eventid: parseInt(eventid)
    });
  };

  handleLeadChange = (isLeading) => {
      this.setState({isLeading});
  };

  checkIfNotExists = (reg) => {
      const { eventid } = this.state;
      return (reg["eventid"] != eventid);
  };

  registerEventHandler = () => {
      const { levelid, styleid, eventid, partner, isLeading, user_competition_events } = this.state;
      const button_enabled = (eventid != null) && (isLeading != null) && (partner != null)
      console.log(user_competition_events)
      console.log(eventid)
      if (button_enabled) {
          if (!user_competition_events.every(this.checkIfNotExists)) {
              console.log(user_competition_events.every(this.checkIfNotExists));
              alert('You are already registered for this event!');
              return false
          } else if (this.competitor_id == partner) {
              alert('This is a partner dance competition silly, dance with somebody else!');
              return false
          }
          var leadcompetitorid = partner;
          var followcompetitorid = this.competitor_id;
          if (isLeading == 'Leading') {
            leadcompetitorid = this.competitor_id;
            followcompetitorid = partner;
          }
            fetch("/api/create_partnership", {
                method: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    leadcompetitorid: leadcompetitorid,
                    followcompetitorid: followcompetitorid,
                    eventid: eventid,
                    competitionid: this.competition_id
                })
            }).then((response) => {
                fetch("/api/create_paymentrecord", {
{'fraction_non_alphanumeric': 0.13416061812221963, 'fraction_numerical': 0.0001560914696011863, 'mean_word_length': 2.2228370221327967, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 54, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6620119', 'n_tokens_mistral': 3747, 'n_tokens_neox': 3734, 'n_words': 793}