import React from "react";
import Form from "react-jsonschema-form";

import schema from "../../../schemas/tracking_link.json";

const uiSchema = {};
const log = type => console.log.bind(console, type);

function dec2hex(dec) {
  return ("0" + dec.toString(16)).substr(-2);
}

function generateSlug() {
  var arr = new Uint8Array(10 / 2);
  window.crypto.getRandomValues(arr);
  return Array.from(arr, dec2hex).join("");
}

interface TrackingLinkFormProps {
  trackingLink: any;
  onSubmit: (data: any) => void;
}

export default class TrackingLinkForm extends React.Component<TrackingLinkFormProps, any> {
  
  constructor(props) {
    super(props);
    this.state = {
      trackingLink: this.props.trackingLink
    };
  }

  componentDidMount() {
    if (!this.state.trackingLink.slug) {
      const slug = generateSlug();
      this.setState({
        trackingLink: {
          slug
        }
      });
    }
  }

  render() {
    return (
      <Form
        schema={schema}
        uiSchema={uiSchema}
        autocomplete="on"
        formData={this.state.trackingLink}
        onChange={log("changed")}
        onSubmit={this.props.onSubmit}
        onError={log("errors")}
      />
    );
  }
}
