import React from 'react';
import ReactDOM from 'react-dom';
import QueueAnim from 'rc-queue-anim';
import Instance from '../../../../../components/Connection';
import $ from 'jquery';
import dt from 'datatables.net';
import responsive from 'datatables.net-responsive';
import {
  Row,
  Col,
  Grid,
  Table,
} from '@sketchpixy/rubix';
import moment from 'moment';
import ContentAdd from 'material-ui/svg-icons/content/add';
import { Card, CardActions, CardHeader, CardMedia, CardTitle, CardText } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import GoogleAddressComponent from '../../organization/components/GoogleAddressComponent';
import Delete from 'material-ui/svg-icons/action/delete';
import IconButton from 'material-ui/IconButton';


dt.responsive = responsive;
$.dataTable = dt;

const formatTime = function (sec_num) {
  var hours = Math.floor(sec_num / 3600);
  var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
  var seconds = sec_num - (hours * 3600) - (minutes * 60);

  if (hours < 10) { hours = "0" + hours; }
  if (minutes < 10) { minutes = "0" + minutes; }
  if (seconds < 10) { seconds = "0" + seconds; }
  return hours + ':' + minutes + ':' + seconds;
}

const formatPhoneNumber = function (s) {
  var s2 = ("" + s).replace(/\D/g, '');
  var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
  return (!m) ? null : "(" + m[1] + ") " + m[2] + "-" + m[3];
}


const Address = (props) => {
  let list = [];
  let buttonStyle = {
    marginTop: -10
  }

  if (props.addresses && props.addresses !== null && props.addresses.length > 0) {
    const handleRemoveAddress = (a) => {
      if (props.onAddressRemoved) {
        props.onAddressRemoved(a);
      }
    }

    list = props.addresses.map((c, i) => {
      let name = c.name;
      switch (c.address_type) {
        case "home":
        case "work":
          name = c.address_type_name;
      }
      if (i === 0) {
        return (<div className="row metrics" key={c.id}>
          <div className="col-xl-4 col-xs-4 col-md-4">
            <span className="metric-info">Name</span>
            <span className="metric">{name}</span>
          </div>
          <div className="col-xl-6 col-xs-6 col-md-6">
            <span className="metric-info">Address</span>
            <span className="metric">{c.address}</span>
          </div>
          <div className="col-xl-2 col-xs-2 col-md-2">
            <span className="metric-info">Actions</span>
            <span className="metric"><IconButton onTouchTap={(e) => handleRemoveAddress(c)} style={buttonStyle}><Delete /></IconButton></span>
          </div>
        </div>);
      } else {
        return (<div className="row metrics" key={c.id}>
          <div className="col-xl-4 col-xs-4 col-md-4">
            <span className="metric">{name}</span>
          </div>
          <div className="col-xl-6 col-xs-6 col-md-6">
            <span className="metric">{c.address}</span>
          </div>
          <div className="col-xl-2 col-xs-2 col-md-2">
            <span className="metric"><IconButton onTouchTap={(e) => handleRemoveAddress(c)} style={buttonStyle}><Delete /></IconButton></span>
          </div>
        </div>);
      }
    });
  }

  return (
    <div className="box box-default">
      <div className="box-body">
        <div className="row">
          <div className="col-xl-12 col-xs-12 col-md-12">
            <div className="row metrics">
              <div className="col-xl-9 col-xs-9 col-md-9">
                <span className="metric">Addresses</span>
              </div>
              <div className="col-xl-3 col-xs-3 col-md-3">
                <GoogleAddressComponent title={"Member Address"} buttonValue={"+Address"} onSelectAddress={props.onAddressAdded} showType={true} />
              </div>
            </div>
            {list}
          </div>
        </div>
      </div>
    </div>
  )
};

const Main = (props) => {
  return (
    <div className="row">
      <div className="col-xl-12">
        <Header user={props.user} />
      </div>
      <div className="col-xl-6">
        <Address addresses={props.user.addresses} onAddressAdded={props.onAddressAdded} onAddressRemoved={props.onAddressRemoved} />
      </div>
      <div className="col-xl-12">
        <DatatableComponent rides={props.rides} />
      </div>
    </div>
  )
};

class DatatableComponent extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;
    this.state = {
      items: [],
      data: [],
      dataTable: null,
      rides: [],
    }

    this.getDatatable = this.getDatatable.bind(this);
  }


  componentWillReceiveProps(nextProps) {
    const rides = nextProps.rides;
    const state = this;
    if (state.state.rides.length === 0) {

      let list = rides.map(v => {
        var data = {
          id: v.ride_uuid,
          user_id: v.user.useruuid,
          memberName: v.user.name,
          time: '',
          pickup: '',
          destination: '',
          status: v.status.value,
          eta: 0,
          duration: 0,
          mileage: '0 miles',
          vehicle: v.vehicle.color + ' ' + v.vehicle.make + ' ' + v.vehicle.model,
          plate: v.vehicle.license_plate,
          mobile: v.driver.phone_number,
          lyftID: v.internal_id,
          rideID: v.ride_uuid
        };

        if (!data.mobile) data.mobile = '';

        if (v.visit_date) data.time = new Date(v.visit_time);

        if (v.route.origin.name && v.route.origin.name !== '') data.pickup = v.route.origin.name;
        else data.pickup = v.route.origin.address;

        if (v.route.destination.name && v.route.destination.name !== '') data.destination = v.route.destination.name;
        else data.destination = v.route.destination.address;

        if (v.route.distance) data.mileage = v.route.distance + ' miles';
        if (v.route.duration) data.duration = formatTime(v.route.duration);
        if (v.route.eta) data.eta = formatTime(v.route.eta);

        return data;
      })

      $.fn.dataTable.moment = function (format, locale) {
        var types = $.fn.dataTable.ext.type;

        // Add type detection
        types.detect.unshift(function (d) {
          return moment(d, format, locale, true).isValid() ?
            'moment-' + format :
            null;
        });

        // Add sorting method - use an integer for the sorting
        types.order['moment-' + format + '-pre'] = function (d) {
          return moment(d, format, locale, true).unix();
        };
      };

      $.fn.dataTable.moment('MM/DD/YYYY h:mm a');

      state.setState(Object.assign(state.state, { rides: list }));
      if (state.state.rides.length > 0) {
        this.getDatatable();
        $(ReactDOM.findDOMNode(state.example))
          .addClass('nowrap')
          .dataTable({
            responsive: true,
            data: state.state.rides,
            columns: [
              {
                data: "time",
                fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                  $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + moment(oData.time).format('MM/DD/YYYY h:mm a') + "</a>");
                }
              },
              { data: "status" },
              {
                data: "pickup",
                fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                  $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.pickup + "</a>");
                }
              },
              {
                data: "destination",
                fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                  $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.destination + "</a>");
                },
                render: function (data, type, row) {
                  return "<a href='/#/app/page/map/" + row.id + "'>" + row.destination + "</a>";
                }
              },

              { data: "eta" },
              { data: "duration" },
              { data: "mileage" },
              { data: "vehicle" },
              { data: "plate" },
              { data: "mobile" },
              {
                data: "lyftID",
                fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                  $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.lyftID + "</a>");
                },
                render: function (data, type, row) {
                  return "<a href='/#/app/page/map/" + row.id + "'>" + row.lyftID + "</a>";
                }
              },
              {
                data: "rideID",
                fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                  $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.rideID + "</a>");
                },
                render: function (data, type, row) {
                  return "<a href='/#/app/page/map/" + row.id + "'>" + row.rideID + "</a>";
                }
              }
            ],
            dom: 'Bfrtip',
            buttons: [
              'copy', 'pdf'
            ],
            //  columns: TABLE_COLUMNS_SORT_STYLE,
            responsive: true,
            "bStateSave": true,
            details: {
              type: 'inline'
            },
            columnDefs: [
              { targets: [-1, -3], orderable: true, className: 'dt-body-right mdl-data-table__cell--non-numeric' }
            ],
            order: [[0, 'desc']]
          });

        this.decorateButtons();
        this.decorateSelect();
        this.decorateSearchBar();
        this.decorateColumns();
      }
    }
  }

  componentDidMount() {
    const rides = this.props.rides;
    const state = this;

    if (rides.length > 0) {
      this.getDatatable();
      let list = rides.map(v => {
        var data = {
          id: v.ride_uuid,
          user_id: v.user.useruuid,
          memberName: v.passenger.first_name + ' ' + v.passenger.last_name,
          time: '',
          pickup: '',
          destination: '',
          status: v.status.value,
          eta: 0,
          duration: 0,
          mileage: '0 miles',
          vehicle: v.vehicle.color + ' ' + v.vehicle.make + ' ' + v.vehicle.model,
          plate: v.vehicle.license_plate,
          mobile: v.driver.phone_number,
          lyftID: v.internal_id,
          rideID: v.ride_uuid
        };

        if (!data.mobile) data.mobile = '';

        if (v.visit_date) data.time = new Date(v.visit_time);

        if (v.route.origin.name && v.route.origin.name !== '') data.pickup = v.route.origin.name;
        else data.pickup = v.route.origin.address;

        if (v.route.destination.name && v.route.destination.name !== '') data.destination = v.route.destination.name;
        else data.destination = v.route.destination.address;

        if (v.route.distance) data.mileage = v.route.distance + ' miles';
        if (v.route.duration) data.duration = formatTime(v.route.duration);
        if (v.route.eta) data.eta = formatTime(v.route.eta);

        return data;
      })

      $.fn.dataTable.moment = function (format, locale) {
        var types = $.fn.dataTable.ext.type;

        // Add type detection
        types.detect.unshift(function (d) {
          return moment(d, format, locale, true).isValid() ?
            'moment-' + format :
            null;
        });

        // Add sorting method - use an integer for the sorting
        types.order['moment-' + format + '-pre'] = function (d) {
          return moment(d, format, locale, true).unix();
        };
      };

      $.fn.dataTable.moment('MM/DD/YYYY h:mm a');

      state.setState(Object.assign(state.state, { rides: list }));

      $(ReactDOM.findDOMNode(state.example))
        .addClass('nowrap')
        .dataTable({
          responsive: true,
          data: state.state.rides,
          columns: [
            {
              data: "time",
              fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + moment(oData.time).format('MM/DD/YYYY h:mm a') + "</a>");
              }
            },
            { data: "status" },
            {
              data: "pickup",
              fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.pickup + "</a>");
              }
            },
            {
              data: "destination",
              fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.destination + "</a>");
              },
              render: function (data, type, row) {
                return "<a href='/#/app/page/map/" + row.id + "'>" + row.destination + "</a>";
              }
            },

            { data: "eta" },
            { data: "duration" },
            { data: "mileage" },
            { data: "vehicle" },
            { data: "plate" },
            { data: "mobile" },
            {
              data: "lyftID",
              fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.lyftID + "</a>");
              },
              render: function (data, type, row) {
                return "<a href='/#/app/page/map/" + row.id + "'>" + row.lyftID + "</a>";
              }
            },
            {
              data: "rideID",
              fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
                $(nTd).html("<a href='/#/app/page/map/" + oData.id + "'>" + oData.rideID + "</a>");
              },
              render: function (data, type, row) {
                return "<a href='/#/app/page/map/" + row.id + "'>" + row.rideID + "</a>";
              }
            }
          ],
          dom: 'Bfrtip',
          buttons: [
            'copy', 'pdf'
          ],
          //  columns: TABLE_COLUMNS_SORT_STYLE,
          responsive: true,
          "bStateSave": true,
          details: {
            type: 'inline'
          },
          columnDefs: [
            { targets: [-1, -3], orderable: true, className: 'dt-body-right mdl-data-table__cell--non-numeric' }
          ],
          order: [[0, 'desc']]
        });

      this.decorateButtons();
      this.decorateSelect();
      this.decorateSearchBar();
      this.decorateColumns();
    }
  }

  getDatatable() {
    let dataTable = (
      <Table ref={(c) => this.example = c} className='display' cellSpacing='0' width='100%'>
        <thead>
          <tr>
            <th>Pickp Time</th>
            <th>Status</th>
            <th>Origin</th>
            <th>Destination</th>
            <th>ETA</th>
            <th>Duration</th>
            <th>Mileage</th>
            <th>Vehicle</th>
            <th>Plate</th>
            <th>Driver Phone</th>
            <th>Lyft ID</th>
            <th>Ride ID</th>
          </tr>
        </thead>
      </Table>)
    this.setState(Object.assign(this.state, { dataTable: null }));
    this.setState(Object.assign(this.state, { dataTable: dataTable }));
  }

  decorateColumns() {
    let cols = $('td');
    let colStyle = {
      'font-family': 'Roboto, sans-serif',
      'font-size': '13px',
      'font-weight': '300',
      'text-align': 'left',
    };
    cols.css(colStyle);
    cols.removeClass('sorting_1');

    let headers = $('th');
    let headerStyle = {
      'color': 'rgb(158, 158, 158)',
      'text-align': 'left',
      'font-weight': '600',
      'font-size': '12px'
    };
    headers.css(headerStyle);

    let oddRows = $('.odd');
    let evenRows = $('.even');

    let oddStyle = {
      'background': 'rgba(127, 221, 233, 0.4)',
      'text-shadow': 'none',
      'border-bottom': '1px solid rgb(224, 224, 224)',
      'color': 'rgba(0, 0, 0, 0.87)',
      'height': '45px'
    };
    oddRows.css(oddStyle);

    let evenStyle = oddStyle;
    evenStyle['background'] = '#fff';

    evenRows.css(evenStyle);
  }

  decorateSelect() {
    let instance = this;
    let selectElement = $('select[class]');
    selectElement.addClass('mdl');

    selectElement.click(function () {
      instance.decorateButtons();
    });

    let selectLabel = $('#DataTables_Table_0_length > label');
    let style = {
      'color': 'rgb(158, 158, 158)',
      'text-align': 'left',
      'font-weight': '500',
      'font-size': '11px'
    };
    selectLabel.css(style);
  }

  decorateSearchBar() {
    let instance = this;

    let searchbar = $('input[type="search"]');
    searchbar.bind('input', function () {
      instance.decorateButtons();
      instance.decorateColumns();
    });

    searchbar.addClass('mdl-textfield__input');
    searchbar.attr('placeholder', '');

    let searchLabel = $('#DataTables_Table_0_filter > label');
    searchLabel.css({ 'color': '#fff' });
    searchbar.css({ 'color': 'rgb(158, 158, 158)' })

    let searchFilter = $('#DataTables_Table_0_filter');
    searchFilter.append('<svg viewBox="0 0 24 24" style="display: inline-block; color: rgba(0, 0, 0, 0.87); fill: currentcolor; height: 24px; width: 24px; user-select: none; transition: all 450ms cubic-bezier(0.23, 1, 0.32, 1) 0ms; margin-top: 12px;"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg>');
  }

  decorateButtons() {
    let instance = this;
    let paginateButtons = $('a.paginate_button');
    paginateButtons.addClass('mdl-button');

    let selectedButton = $('a.paginate_button.current');
    selectedButton.addClass('mdl-button mdl-button--raised mdl-button--colored');

    let style = {
      'background': 'rgb(0, 188, 212)',
      'font-weight': '400',
    };
    selectedButton.css(style);

    paginateButtons.click(function () {
      instance.decorateButtons();
      instance.decorateColumns();
    });

    let sortingButtons = $('th.sorting, th.sorting_asc, th.sorting_desc');
    sortingButtons.click(function () {
      instance.decorateButtons();
      instance.decorateColumns();
    });

    let entriesLabel = $('#DataTables_Table_0_info');
    entriesLabel.css({
      'color': 'rgb(158, 158, 158)',
      'text-align': 'left',
      'font-weight': '400',
      'font-size': '12px'
    });
  }

  render() {
    return (
      <div className="box box-default">
        <div className="box-body">
          <div className="row">

            <div className="col-xl-12 col-xs-12 col-md-12">
              <h2 className="article-title">Rides for this Member</h2>
              <Table ref={(c) => this.example = c} className='display' cellSpacing='0' width='100%'>
                <thead>
                  <tr>
                    <th>Pickp Time</th>
                    <th>Status</th>
                    <th>Origin</th>
                    <th>Destination</th>
                    <th>ETA</th>
                    <th>Duration</th>
                    <th>Mileage</th>
                    <th>Vehicle</th>
                    <th>Plate</th>
                    <th>Driver Phone</th>
                    <th>Lyft ID</th>
                    <th>Ride ID</th>
                  </tr>
                </thead>
              </Table>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

const Rides = (props) => {
  let rides = [];
  let list = [];

  if (props.user.rides && props.user.rides !== null && props.user.rides.length > 0) {
    rides = props.user.rides;
    rides.forEach(c => {
      let visit_time = ""
      if (c.visit_time) visit_time = moment(new Date(c.visit_time)).format('MM/DD/YYYY h:mm a');
      list.push(
        <div className="box" key={c.ride_uuid}>
          <div className="box-body">
            <div className="row">
              <div className="col-xl-6 col-xs-6 col-md-6">
                <span><strong>Pickup:</strong><br /><a href={"/#/app/page/map/" + c.ride_uuid}>{c.route.origin.name}</a></span>
              </div>
              <div className="col-xl-6 col-xs-6 col-md-6">
                <span><strong><a href={"/#/app/page/map/" + c.ride_uuid}>Details...</a></strong></span>
              </div>
              <div className="col-xl-12 col-xs-12 col-md-12">
                <span><strong>Destination:</strong><br /><a href={"/#/app/page/map/" + c.ride_uuid}>{c.route.destination.name}</a></span>
              </div>
              <div className="col-xl-6 col-xs-6 col-md-6">
                <span><strong>Date:</strong><br />{visit_time}</span>
              </div>
              <div className="col-xl-6 col-xs-6 col-md-6">
                <span><strong>Status:</strong><br />{c.status.value}</span>
              </div>
            </div>
          </div>
        </div>);
    }, this);
  }

  return (
    <div className="box box-default">
      <div className="box-body">
        <div className="row">
          <div className="col-xl-12 col-xs-12 col-md-12">
            <div className="box box-transparent">
              <div className="box-body">
                <div className="row metrics">
                  <div className="col-xl-12 col-xs-12 col-md-12">
                    <span className="metric">Rides</span>
                  </div>
                </div>
                {list}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
};

const ContactInfo = (props) => {
  let contact = [];
  let list = [];
  if (props.user.contacts && props.user.contacts !== null && props.user.contacts.length > 0) {
    contact = props.user.contacts;
    contact.forEach(c => {
      let contact = c.contact
      if (c.type.key === 'phone') {
        contact = contact.replace('+1', '');
        contact = formatPhoneNumber(contact);
      }

      list.push(<div className="row metrics" key={c.type.key + c.contact}>
        <div className="col-xl-6 col-xs-6 col-md-6">
          <span className="metric-info">{c.type.value}:</span>
        </div>
        <div className="col-xl-6 col-xs-6 col-md-6">
          <span className="metric-info">{contact}</span>
        </div>
      </div>);
    }, this);
  }

  return (
    <div className="box box-default">
      <div className="box-body">
        <div className="row">
          <div className="col-xl-12 col-xs-12 col-md-12">
            <div className="box box-transparent">
              <div className="box-body">
                <div className="row metrics">
                  <div className="col-xl-12 col-xs-12 col-md-12">
                    <span className="metric">Contact Info</span>
                  </div>
                </div>
                {list}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
};

const Header = (props) => {
  let gender = "Other";
  if (props.user.gender === "M") gender = "Male";
  if (props.user.gender === "F") gender = "Female";

  let birthdate = "";
  if (props.user.birthdate) birthdate = moment(new Date(props.user.birthdate)).format('MM/DD/YYYY');

  let phonenumber = "";
  if (props.user.phonenumber && props.user.phonenumber !== null && props.user.phonenumber !== "") {
    phonenumber = props.user.phonenumber
    phonenumber = phonenumber.replace('+1', '');
    phonenumber = formatPhoneNumber(phonenumber);
  }

  return (
    <div className="box box-default">
      <div className="box-body">
        <RaisedButton href={"#/app/form/steppers/" + props.user.useruuid} label="Ride" labelPosition="after" primary icon={<ContentAdd />} />
        <h2 className="article-title">Member Details </h2>

        <div className="row">
          <div className="col-xl-12">

            <div className="row metrics">
              <div className="col-md-2">
                <span className="metric-info">Full Name</span>
                <span className="metric">{props.user.name}</span>
              </div>
              <div className="col-md-2">
                <span className="metric-info">Subscriber ID</span>
                <span className="metric">{props.user.member}</span>
              </div>
              <div className="col-md-2">
                <span className="metric-info">Gender</span>
                <span className="metric">{gender}</span>
              </div>

              <div className="col-md-2">
                <span className="metric-info">Birth Date</span>
                <span className="metric">{birthdate}</span>
              </div>

              <div className="col-md-2">
                <span className="metric-info">Mobile</span>
                <span className="metric">{phonenumber}</span>
              </div>
              <div className="col-xl-2">
                <span className="metric-info">Email</span>
                <span className="metric">{props.user.email}</span>
              </div>
            </div>
          </div>
        </div>

      </div>
    </div>
  )
};

class Member extends React.Component {
  constructor(props) {
    super(props);
    this.props = props;

    this.getMember = this.getMember.bind(this);
    this.handleAddressAdded = this.handleAddressAdded.bind(this);
    this.handleAddressRemoved = this.handleAddressRemoved.bind(this);
  }

  state = {
    user: {
      "useruuid": "",
      "name": "",
      "gender": "",
      "member": "",
      "birthdate": "",
      "email": "",
      "phonenumber": "",
      "profile": "",
      "contacts": [],
      "rides": [],
      "addresses": [],
    }
  }

  componentDidMount() {
    const useruuid = this.props.params.user_uuid;
    this.getMember(useruuid);
  }

  getMember(useruuid) {
    Instance.getRawConn().get(`/v1/nemt/users/member/${useruuid}`)
      .then(res => {
        if (res.data.rides && res.data.rides.length > 0) {
          res.data.rides = res.data.rides.map(ride => {
            if (!ride.driver.first_name) {
              ride.driver = {
                image_url: '',
                rating: '',
                first_name: '',
                phone_number: ''
              }
            }

            if (!ride.vehicle.plate) {
              ride.vehicle = {
                color: '',
                image_url: '',
                license_plate: '',
                license_plate_state: '',
                make: '',
                model: '',
                year: 0
              }
            }

            return ride;
          })
        } else {
          res.data.rides = [];
        }
        this.setState(Object.assign(this.state, { user: res.data }));
      })
      .catch(console.error);
  }

  handleAddressAdded(address) {
    const user_uuid = this.props.params.user_uuid;
    const self = this;

    const addressObj = {
      "id": address.id,
      "name": address.name,
      "address": address.address,
      "address_type": address.address_type,
      "lat": address.lat,
      "lng": address.lng,
      "type": address.type,
      "address": address.text,
    }

    Instance.getRawConn().post(`/v1/nemt/users/member/${user_uuid}/address`, addressObj)
      .then(res => {
        this.getMember(user_uuid);
      })
      .catch(console.error);
  }

  handleAddressRemoved(address) {
    const user_uuid = this.props.params.user_uuid;
    const self = this;

    Instance.getRawConn().put(`/v1/nemt/users/member/${user_uuid}/address/${address.address_uuid}`).then(res => {
      this.getMember(user_uuid);
    }).catch(console.error);
  }

  render() {
    return (
      <div className="container-fluid no-breadcrumbs page-dashboard">
        <QueueAnim type="bottom" className="ui-animate">
          <Main user={this.state.user} rides={this.state.user.rides}
            onAddressAdded={this.handleAddressAdded} onAddressRemoved={this.handleAddressRemoved} />
        </QueueAnim>
      </div>)
  }
}
module.exports = Member;
