_                     = require('lodash')
moment                = require('moment')
dispatcher            = require('../../common/js/dispatcher')
default_params        = require('./strategies/default_params.coffee')
aviasales_ru_params   = require('./strategies/aviasales_ru_params.coffee')
short_params_parser   = require('./strategies/short_params.coffee')
PlacesRestorer        = require('./places_restorer.coffee')
utils                 = require('../../common/js/utils.coffee')
cookies               = require('../../common/js/cookies.coffee')
marker                = require('../../common/js/marker.coffee')
{getAuid}             = require('../../common/js/auid')
metrics               = require('../../common/js/metrics.coffee')
short_url             = require('../../common/js/short_url.coffee')
cookie_params         = require('../../common/js/cookie_params.coffee')
config                = require('../../../config/config')

DEFAULT_CURRENCY = 'usd'

# TODO: refactor coz you can compare dates as strings
# '2015-12-06' < '2015-11-05'
normalize_dates = (params) ->
  if !params.segments
    return

  prev = moment()
  for segment in params.segments
    continue if !segment.date

    seg_moment = moment(segment.date)
    if prev.diff(seg_moment, 'days') > 1
      segment.date = prev.format('YYYY') + '-' + seg_moment.format('MM-DD')

    prev = seg_moment
  params

is_valid_dates = (params) ->
  now_moment = moment()
  depart_moment = moment(params.segments[0].date)

  valid = depart_moment.diff(now_moment, 'days') > -1

  if valid and params.segments.length == 2
    return_moment = moment(params.segments[1].date)
    valid = return_moment.diff(now_moment, 'days') >= 0 and return_moment.diff(depart_moment, 'days') >= 0

  valid

search_from_params = (should_replace_history = true) ->
  parsed_params = _.extend(
    {},
    default_params,
    aviasales_ru_params(window.location.search),
    short_params_parser(window.location.pathname)
  )

  # Parse AUID
  getAuid (auid) ->
    dispatcher.send 'auid_restored', auid, 'parser'

  # Parse cookies into params
  if (!parsed_params.segments[0].origin and !parsed_params.segments[0].origin_name) or (!parsed_params.segments[0].destination and !parsed_params.segments[0].destination_name)
    if !_.isEmpty(parsed_params) and !!parsed_params.with_request
      metrics.reach_goal('NOT_ENOUGH_PARAMS', {path: window.location.search})
    _.extend(parsed_params, cookie_params.get_params())

  # Prepare correct dates
  # normalize_dates(parsed_params)

  # Country
  host = _.findLast(config.HOSTS, (n) => n.host == location.hostname) or config.HOSTS[0];
  dispatcher.send('host_updated', host, 'parser');

  # Currency
  defaultCurrency = config.HOSTS_INDEX[host.code].currency;
  currency = parsed_params.currency or (cookies.get('currency_code') && cookies.get('currency_code').toLowerCase()) or defaultCurrency
  dispatcher.send('currency_updated', currency.toLowerCase(), 'parser')

  # Handle marker
  dispatcher.send 'marker_restored', marker.handle_marker(parsed_params.marker), 'parser'

  if not is_valid_dates(parsed_params)
    dispatcher.send('wrong_search_dates', null, 'parse')
    parsed_params.with_request = false

  if parsed_params['with_request']
    dispatcher.send('start_search', {request_id: utils.generate_id(), params: parsed_params}, 'parser')
  else
    dispatcher.send('search_not_started', null, 'parse')

  new PlacesRestorer(parsed_params, (restored_params) ->
    dispatcher.send('places_restored', restored_params, 'parse')
    if parsed_params.with_request and should_replace_history and !_.isUndefined(window.history?.replaceState)
      console.log('short url history state was pushed here: ', short_url(restored_params))
      # window.history.replaceState(null, null, short_url(restored_params))
  )

track_redirect_time = ->
  search_init_stamp = cookies.get('search_init_stamp')
  if search_init_stamp and +search_init_stamp > 0
    current_stamp = new Date().getTime()
    cookies.set('search_init_stamp', '0', 'Thu, 01 Jan 1970 00:00:01 GMT')
    diff = current_stamp - +search_init_stamp
    metrics.reach_goal('REDIRECT_TIME', null, diff)
    _gaq?.push(['_trackTiming', 'search_page', 'redirect_time', diff, undefined, 100])

dispatcher.on('components_loaded', ->
  search_from_params(true)
  track_redirect_time()
  setTimeout(->
    window.addEventListener 'popstate', ((e) ->
      search_from_params(false)
    ), false
  , 4000)
)

module.exports = search_from_params
