_ = require('lodash')
utils = require('../../common/js/utils.coffee')
dispatcher = require('../../common/js/dispatcher')
converter = require('../../common/js/converter')
{ Form } = require('jr-form')

TRIP_CLASSES =
  'Y': 'economy',
  'W': 'premiumEconomy',
  'C': 'business',
  'F': 'first'

URL_TRIP_CLASSES = _.invert(TRIP_CLASSES)

module.exports = (root) ->
  form = new Form(root.querySelector('.simple-form'))

  state =
    request_id: null

  fillFormWithParams = (params) ->
    tripType = if (params.segments?.length == 1 && params.with_request) then 'TRIP_TYPE_ONE_WAY' else 'TRIP_TYPE_ROUND_TRIP'
    if params.segments[0]
      firstSegment = params.segments[0]

      formattedParams = {
        "origin": {
          "iata": firstSegment.origin,
          "name": firstSegment.origin_name
          "type": "airport"
        },
        "destination": {
          "iata": firstSegment.destination,
          "name": firstSegment.destination_name,
          "type": "airport"
        },
        "departDate": firstSegment.date,
        "tripType": tripType,
        "options": {
          "adults": params.passengers?.adults,
          "children": params.passengers?.children,
          "infants": params.passengers?.infants,
          "tripClass": TRIP_CLASSES[params.trip_class]
        }
      }

      formattedParams.returnDate = params.segments[1].date if params.segments[1]?.date
      form.setSearchParams formattedParams

  setSearchURL = () -> window.history.pushState(null, null, form.model.getURL().split('/')[2])

  form.beforeSubmit = () ->
    # Detect and redirect to open search.
    if this.model.segments.length > 0 && this.model.segments[0].destination.selected.type == 'country'
      window.location.href = form.model.getURL()
      return true

    # Start normal search.
    segments = () =>
      unless this.model.multiCity
        segment = this.model.segments[0]
        parsedSegment = {
          origin: segment.origin.selected.iata,
          origin_name: segment.origin.selected.name,
          destination: segment.destination.selected.iata,
          destination_name: segment.destination.selected.name,
          date: segment.date.departDate.format('YYYY-MM-DD')
        }
        if segment.date.tripType is 'TRIP_TYPE_ONE_WAY'
          [parsedSegment]
        else
          [
            parsedSegment, {
              origin: segment.destination.selected.iata,
              origin_name: segment.destination.selected.name,
              destination: segment.origin.selected.iata,
              destination_name: segment.origin.selected.name,
              date: segment.date.returnDate.format('YYYY-MM-DD')
            }
          ]
    passengers =
      'adults': this.model.options.adults
      'children': this.model.options.children
      'infants': this.model.options.infants

    dispatcher.send('start_search', {
      request_id: utils.generate_id(),
      params: {
        "segments": segments(),
        "passengers": passengers
        "trip_class": URL_TRIP_CLASSES[this.model.options.tripClass],
        "locale": LOCALE,
        "host": "search.aviasales.ru",
        "currency": "rub"
      },
      sort_order: 'price'
    }, 'form')

    setSearchURL()
    return true


  dispatcher.on('start_search', (event, {request_id, params}, source) ->
    if source is 'history'
      fillFormWithParams params
      setSearchURL()

    # Suppose to be kinda handling of start new search while old one is still in progress
    if state.request_id
      dispatcher.send 'stop_search', {request_id: state.request_id}, 'form'
  )

  dispatcher.on 'places_restored', (event, params) -> fillFormWithParams params

  dispatcher.on 'currency_updated', (event, currency_code) ->
    prices = document.getElementsByClassName('js-price')
    for price in prices
      ruPrice = price.data('ruPrice')
      newPrice = converter.format(ruPrice)
      price.textContent = newPrice

  dispatcher.on 'currencies_updated', (event) ->
    window.Core?.Utils?.changeCurrencies = (currencyCode, ruPrice) => converter.convert(ruPrice, {to: currencyCode});

