import { action, observable, autorun, asReference } from 'mobx';
import axios from 'axios';

class PasteViewStore {

  constructor(props) {
    this.props = props;

    // If we got here from the edit link, let's copy over the stored text
    this.defaultTxt = this.props.pathname == '/edit' ?
      this.props.ViewsStore.current.text : '';

    this.defaultTitle = this.props.pathname == '/edit' ?
      this.props.ViewsStore.current.title : '';

    this.setCurrentView();
  }

  @observable title = this.defaultTitle;
  @observable name = '';
  @observable text = this.defaultTxt;
  @observable expiration = '1 days';
  @observable privacyPublic = true;
  @observable redirect = '';
  @observable errors = [];

  @action
  setCurrentView = () => {
    this.props.ViewsStore.current = observable({
      currentView: 'PasteView',
      saveButton: asReference(this.saveButton)
    });
  };

  @action
  handleChange = (event) => this[event.target.name] = event.target.value;

  @action
  getErrors = () => this.errors;

  @action
  saveButton = () => {
    // Do some validation and formatting
    console.log('save button pressed');
    let errors = [];
    if (!this.text || this.text.length < 3) {
      errors.push('Please enter more text to save.');
    }

    if (errors.length) {
      this.errors = errors;
    } else {
      axios.post('/api', {
        title: this.title,
        text: this.text,
        name: this.name,
        expiration: this.expiration,
        privacyPublic: this.privacyPublic
      }).then(res => {
        this.redirect = res.data.key;
      })
        .catch(err => {
          errors.push(err);
          this.errors = errors;
      });
    }
  };

  @action
  handlePrivacyRadio = (event) =>
    this.privacyPublic = event.currentTarget.value === 'public'

}

export default PasteViewStore;

@@ -84,16 +84,45 @@
 'axios';
+%0Aimport cookie from 'cookie';
 %0A%0Aclass 
@@ -187,16 +187,181 @@
 props;%0A%0A
+    this.cookies = cookie.parse(document.cookie);%0A    this.defaultExpiration = this.cookies.expiration %7C%7C '1 days';%0A    this.defaultName = this.cookies.name %7C%7C '';%0A%0A
     // I
@@ -706,16 +706,22 @@
 ultTitle
+ %7C%7C ''
 ;%0A  @obs
@@ -734,16 +734,36 @@
 e name =
+ this.defaultName %7C%7C
  '';%0A  @
@@ -795,16 +795,22 @@
 faultTxt
+ %7C%7C ''
 ;%0A  @obs
@@ -830,24 +830,38 @@
 ation = 
-'1 days'
+this.defaultExpiration
 ;%0A  @obs
@@ -1546,24 +1546,24 @@
 s = errors;%0A
-
     %7D else %7B
@@ -1563,16 +1563,191 @@
  else %7B%0A
+      // Set the cookies%0A      document.cookie = cookie.serialize('name', String(this.name));%0A      document.cookie = cookie.serialize('expiration', String(this.expiration));%0A
       ax

save last name and expiration prefs