@extends('currencies.base')

@section('title')
  Moneda - <span class="c_name"></span>
@endsection

@section('content')
  <h3 class="ui header c_code"></h3>
  <table class="ui table">
    <thead>
      <th>Alias</th>
      <th class="right aligned" id="add_alias">
        <i class="plus icon"></i>
      </th>
    </thead>
    <tbody id="aliases"></tbody>
  </table>
  <table class="ui table">
    <thead>
      <th>Url</th>
      <th class="right aligned" id="add_source">
        <i class="plus icon"></i>
      </th>
    </thead>
    <tbody id="sources"></tbody>
  </table>
  <table class="ui table">
    <thead>
      <tr>
        <th>Fecha</th>
        <th>Valor</th>
        <th class="right aligned" id="add_value">
          <i class="plus icon"></i>
        </th>
      </tr>
    </thead>
    <tbody id="values"></tbody>
  </table>
  <div class="ui modal" id="add_values">
    <div class="header">
      Agregar Valor para <span class="c_name"></span>
    </div>
    <div class="content">
      <form class="ui form">
        <div class="inline field">
          <label>Fecha</label>
          <div class="ui calendar">
            <div class="ui input left icon">
              <i class="calendar icon"></i>
              <input type="text" placeholder="Fecha/Hora" name="fecha" />
            </div>
          </div>
        </div>
        <div class="inline field">
          <label>Valor</label>
          <input type="text" name="valor" />
        </div>
        <div class="inline field">
          <label>Cambio con</label>
          <div class="ui dropdown">
            <input type="hidden" name="base" />
            <div class="default text">
              Cambio
            </div>
            <i class="dropdown icon"></i>
            <div class="menu"></div>
          </div>
        </div>
        <button class="ui button">Agregar</button>
      </form>
    </div>
  </div>
  <div class="ui modal" id="add_sources">
    <div class="header">
      Agregar Fuente para <span class="c_name"></span>
    </div>
    <div class="content">
      <form class="ui form">
        <div class="inline field">
          <label>Url</label>
          <input type="text" name="url" />
        </div>
        <div class="inline field">
          <label>Frecuencia</label>
          <input type="text" name="frecuency" />
          <select name="frec_name" class="ui selection dropdown">
            <option value="minute">Minuto(s)</option>
            <option value="hour">Hora(s)</option>
            <option value="day">D&iacute;a(s)</option>
            <option value="week">Semana(s)</option>
            <option value="month">Mes(es)</option>
            <option value="year">A&ntilde;o(s)</option>
          </select>
        </div>
        <button class="ui button">Agregar</button>
      </form>
    </div>
  </div>
  <div class="ui modal" id="add_aliases">
    <div class="header">
      Agregar Alias para <span class="c_name"></span>
    </div>
    <div class="content">
      <form class="ui form">
        <div class="inline field">
          <label>Alias</label>
          <input type="text" name="alias" />
        </div>
        <button class="ui button">Agregar</button>
      </form>
    </div>
  </div>
@endsection

@push('scripts')
  <script type="text/javascript">
    let aliases = {
      id: '#aliases',
      add_button: '#add_alias',
      add_modal: '#add_aliases',
      loading: '',
      loaded: false,
      aliases: [],
      setup: function() {
        $(this.id).hide()
        $(this.add_button).css('cursor', 'pointer').click((e) => {
          this.add()
        })
        this.buildModal()
      },
      get: function(currency_id, data) {
        if (!this.loaded) {
          this.aliases = data.aliases
          this.populate(currency_id)
          socket.sendMessage('currency.sources', {currency_id: currency_id})
          return
        }
        var url = '{{$urls->api}}/currency/' + currency_id + '/aliases'
        $.getJSON(url, (data) => {
          this.aliases = data.aliases
          this.populate(currency_id)
        })
      },
      buildModal: function() {
        $(this.add_modal).modal()
        $(this.add_modal).find('form').submit((e) => {
          e.preventDefault()
          this.doAdd()
          return false
        })
      },
      populate: function(currency_id) {
        $(this.id).html('')
        $.each(this.aliases, (i, el) => {
          let row = $('<tr></tr>').append(
            $('<td></td>').html(el.alias)
          ).append(
            $('<td></td>').attr('class', 'remove_source right aligned').attr('data-id', el.id).append(
              $('<i></i>').attr('class', 'minus icon')
            ).css('cursor', 'pointer').click((e) => {
              this.remove(currency_id, $(e.currentTarget).attr('data-id'))
            })
          )
          $(this.id).append(row)
        })
        $(this.id).show()
      },
      add: function() {
        $(this.add_modal).find('form').trigger('reset')
        $(this.add_modal).modal('show')
      },
      doAdd: function() {
        let form = $(this.add_modal).find('form')
        let info = {
          alias: form.find("[name='alias']").val()
        }
        var url = '{{$urls->api}}/currency/{{$currency_id}}/aliases/add'
        $(this.add_modal).modal('hide')
        $(this.loading).modal('show')
        $.post(url, JSON.stringify(info), (data) => {
          if (data.aliases[0].created) {
            this.get('{{$currency_id}}')
          }
        }, 'json').then(() => {
          $(this.loading).modal('hide')
        })
      },
      remove: function(id) {
        var url = '{{$urls->api}}/alias/' + id + '/delete'
        $(this.loading).modal('show')
        $.ajax({
          url: url,
          method: 'DELETE',
          dataType: 'json',
          success: (data) => {
            if (data.deleted) {
              this.get()
            }
          }
        }).then(() => {
          $(this.loading).modal('hide')
        })
      }
    }
    let sources = {
      id: '#sources',
      add_button: '#add_source',
      add_modal: '#add_sources',
      loading: '',
      loaded: false,
      sources: [],
      setup: function() {
        $(this.id).hide()
        $(this.add_button).css('cursor', 'pointer').click((e) => {
          this.add()
        })
        this.buildModal()
      },
      get: function(currency_id, data) {
        if (!this.loaded) {
          this.sources = data.sources
          this.populate(currency_id)
          socket.sendMessage('currency.values', {currency_id: currency_id})
          return
        }
        var url = '{{$urls->api}}/currency/' + currency_id + '/sources'
        $.getJSON(url, (data) => {
          this.sources = data.sources
          this.populate(currency_id)
        })
      },
      buildModal: function() {
        $(this.add_modal).modal()
        $(this.add_modal).find('form').submit((e) => {
          e.preventDefault()
          this.doAdd()
          return false
        })
      },
      populate: function(currency_id) {
        $(this.id).html('')
        $.each(this.sources, (i, el) => {
          let row = $('<tr></tr>').append(
            $('<td></td>').html(el.url)
          ).append(
            $('<td></td>').attr('class', 'remove_source right aligned').attr('data-url', el.url).append(
              $('<i></i>').attr('class', 'minus icon')
            ).css('cursor', 'pointer').click((e) => {
              this.remove(currency_id, $(e.currentTarget).attr('data-url'))
            })
          )
          $(this.id).append(row)
        })
        $(this.id).show()
      },
      add: function() {
        $(this.add_modal).find('form').trigger('reset')
        $(this.add_modal).modal('show')
      },
      doAdd: function() {
        let form = $(this.add_modal).find('form')
        let info = {
          url: form.find("[name='url']").val(),
          frecuency: form.find("[name='frecuency']").val() + ' ' + form.find("[name='frec_name']").val()
        }
        var url = '{{$urls->api}}/currency/{{$currency_id}}/sources/add'
        $(this.add_modal).modal('hide')
        $(this.loading).modal('show')
        $.post(url, JSON.stringify(info), (data) => {
          if (data.sources[0].created) {
            this.get('{{$currency_id}}')
          }
        }, 'json').then(() => {
          $(this.loading).modal('hide')
        })
      },
      remove: function(currency_id, url) {
        var url = '{{$urls->api}}/source/' + currency_id + '/' + url + '/delete'
        $(this.loading).modal('show')
        $.ajax({
          url: url,
          method: 'DELETE',
          dataType: 'json',
          success: (data) => {
            if (data.deleted) {
              this.get()
            }
          }
        }).then(() => {
          $(this.loading).modal('hide')
        })
      }
    }
    let values = {
      id: '#values',
      add_button: '#add_value',
      add_modal: '#add_values',
      loading: '',
      values: [],
      loaded: false,
      setup: function() {
        $(this.id).hide()
        this.buildModal()
        $(this.add_button).css('cursor', 'pointer').click((e) => {
          this.add()
        })
      },
      get: function(currency_id, data) {
        if (!this.loaded) {
          if (data.values.length > 0) {
            this.values = data.values
            this.populate(currency_id)
          }
          $(this.loading).modal('hide')
          socket.conn.close()
          return
        }
        var url = '{{$urls->api}}/currency/' + currency_id + '/values'
        $.getJSON(url, (data) => {
          this.values = data.values
          this.populate(currency_id)
        })
      },
      buildModal: function() {
        this.getCurrencies()
        $(this.add_modal).modal()
        $(this.add_modal).find('.ui.calendar').calendar()
        $(this.add_modal).find('form').submit((e) => {
          e.preventDefault()
          this.doAdd()
          return false
        })
        $(this.add_modal).find('.ui.dropdown').dropdown()
      },
      getCurrencies: function() {
        var url = '{{$urls->api}}/currencies'
        $.getJSON(url, (data) => {
          let dp = $(this.add_modal).find('.ui.dropdown')
          vals = []
          $.each(data.currencies, (i, el) => {
            vals.push({name: el.name, value: el.id, text: el.name})
          })
          dp.dropdown('setup menu', {values: vals})
        })
      },
      populate: function(currency_id) {
        $(this.id).html('')
        $.each(this.values, (i, el) => {
          let row = $('<tr></tr>').append(
            $('<td></td>').html(formatDate(new Date(el.date_time)))
          ).append(
            $('<td></td>').html(formatValue(el.value, el.base.code))
          ).append(
            $('<td></td>').attr('class', 'remove_value right aligned').attr('data-base', el.base.id).attr('data-date_time', el.date_time).append(
              $('<i></i>').attr('class', 'minus icon')
            ).css('cursor', 'pointer').click((e) => {
              this.remove(currency_id, $(e.currentTarget).attr('data-base'), $(e.currentTarget).attr('data-date_time'))
            })
          )
          $(this.id).append(row)
        })
        $(this.id).show()
      },
      add: function() {
        $(this.add_modal).find('form').trigger('reset')
        $(this.add_modal).modal('show')
      },
      doAdd: function() {
        let form = $(this.add_modal).find('form')
        let info = {
          date_time: readyDate(new Date(form.find('.ui.calendar').calendar('get date'))),
          value: form.find("[name='valor']").val(),
          base_id: form.find('.ui.dropdown').dropdown('get value')
        }
        var url = '{{$urls->api}}/currency/{{$currency_id}}/values/add'
        $(this.add_modal).modal('hide')
        $(this.loading).modal('show')
        $.post(url, JSON.stringify(info), (data) => {
          if (data.values[0].created) {
            this.get('{{$currency_id}}')
          }
        }, 'json').then(() => {
          $(this.loading).modal('hide')
        })
      },
      remove: function(currency_id, base_id, date_time) {
        var url = '{{$urls->api}}/value/' + currency_id + '/' + base_id + '/' + encodeURI(date_time) + '/delete'
        $(this.loading).modal('show')
        $.ajax({
          url: url,
          method: 'DELETE',
          dataType: 'json',
          success: (data) => {
            if (data.deleted) {
              this.get().then(() => {
                $(this.loading).modal('hide')
              })
            }
          }
        })
      }
    }
    let currency = {
      id: {{$currency_id}},
      data: {
        id: 0,
        name: '',
        code: ''
      },
      map: {
        name: '.c_name',
        code: '.c_code'
      },
      loading: '#loading',
      setup: function() {
        aliases.loading = this.loading
        aliases.setup()
        sources.loading = this.loading
        sources.setup()
        values.loading = this.loading
        values.setup()
        socket.url = '{{$urls->ws}}'
        socket.connect(this.ready, this.getMessage)
      },
      ready: function() {
        socket.sendMessage('currency', {currency_id: '{{$currency_id}}'})
      },
      getMessage: function(e) {
        response = JSON.parse(e.data)
        if (response.request.action == 'currency') {
          currency.get(response.body)
        }
        if (response.request.action == 'currency.aliases') {
          aliases.get(response.request.body.currency_id, response.body)
        }
        if (response.request.action == 'currency.sources') {
          sources.get(response.request.body.currency_id, response.body)
        }
        if (response.request.action == 'currency.values') {
          values.get(response.request.body.currency_id, response.body)
        }
      },
      get: function(data) {
        $.each(this.data, (i, el) => {
          this.data[i] = data.currency[i]
        })
        $.each(this.map, (i, el) => {
          $(el).html(data.currency[i])
        })
        socket.sendMessage('currency.aliases', {currency_id: '{{$currency_id}}'})
      }
    }
    $(document).ready(() => {
      currency.setup()
    })
  </script>
@endpush
