<template>
    <div class="content-container">
        <div class="login-container">
            <div v-if="User">
                <h3>Signed in as {{ User.username }}</h3>
                <button v-on:click="logout">Logout</button>
            </div>
            <div v-else>
                <input id="usernameInput" type="text" v-model="username" placeholder="Username">
                <input id="passwordInput" type="text" v-model="password" placeholder="Password">
                <button v-on:click="createAccount">Create Account</button>
                <button v-on:click="login">Sign In</button>
            </div>
        </div>

        <div class="create-container">
            <h2>Create New Paste</h2>
            <input id="titleInput" type="text" v-model="title" placeholder="Title">
            <label for="contentInput">Content</label>
            <textarea id="contentInput" v-model="content"></textarea>
            <label v-if="User" for="privateInput">Private Paste</label>
            <input v-if="User" type="checkbox" id="privateInput" v-model="privatePaste">
            <button v-on:click="createPaste">Create</button>
        </div>

        <div class="pastes-container">
            <div class="paste" v-for="paste in Pastes">
                <h2>{{ paste.title }}</h2>
                <h3>created by {{ paste.owner ? paste.owner.username : "Anonymous" }}</h3>
                <p>{{ paste.content }}</p>
            </div>
        </div>
    </div>
</template>

<style scoped>
    * {
        margin: 0;
        box-sizing: border-box;
    }

    .paste, .create-container {
        border: 1px solid black;
        margin: 5px;
        padding: 5px;
    }

    .content-container {
        max-width: 80%;
        margin: 0 auto;
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        grid-gap: 10px;
        grid-auto-rows: minmax(100px, auto);
    }

    .login-container {
        grid-column: 1 / 5;
        grid-row: 1;
    }

    /* Create container and children styles */
    .create-container {
        grid-column: 1 / 3;
        grid-row: 2 / 3;

        display: flex;
        flex-direction: column;
    }

    #contentInput {
        flex-grow: 1;
        margin-top: 5px;
        margin-bottom: 5px;
    }

    .pastes-container {
        grid-column: 3 / 5;
        grid-row: 2 / 3;
    }
</style>

<script>
    import PASTES_ALL from '../graphql/PastesAll.gql';
    import PASTES_CREATE from '../graphql/PastesCreate.gql';

    import USER_CREATE from '../graphql/UserCreate.gql';
    import USER_CURRENT from '../graphql/UserCurrent.gql';

    import LOGIN_MUTATION from '../graphql/LoginMutation.gql';
    import LOGOUT_MUTATION from '../graphql/LogoutMutation.gql';

    export default {
      name: 'root',
      components: {},
      data() {
        return {
          username: '',
          password: '',
          title: '',
          content: '',
          privatePaste: false,
          Pastes: [],
          User: null
        }
      },
      methods: {
        createPaste() {
          const title = this.title;
          const content = this.content;
          const privatePaste = this.privatePaste;
          this.title = '';
          this.content = '';
          this.privatePaste = false;

          this.$apollo.mutate({
            mutation: PASTES_CREATE,
            variables: {
              title: title,
              content: content,
              privatePaste: privatePaste,
            },
            update: (store, {data: { PasteCreate } }) => {
              const data = store.readQuery({query: PASTES_ALL});
              data.Pastes.push(PasteCreate.paste);
              store.writeQuery({query: PASTES_ALL, data})
            },
            optimisticResponse: {
              __typename: 'Mutation',
              PasteCreate: {
                __typename: 'PasteCreatePayload',
                paste: {
                  __typename: 'Paste',
                  id: null,
                  title: title,
                  content: content,
                  owner: {
                    __typename: 'User',
                    username: ''
                  }
                }
              }
            }
          }).catch((error) => {
            console.error(error);
            this.title = title;
            this.content = content;
          });
        },

        createAccount() {
          // save the username and password in case of an error
          const username = this.username;
          const password = this.password;
          // clear things early to make the UI feel snappy
          this.username = '';
          this.password = '';

          this.$apollo.mutate({
            mutation: USER_CREATE,
            variables: {
              username: username,
              password: password,
            },
            update: (store, { data: { UserCreate }}) => {
              const data = store.readQuery({query: USER_CURRENT});
              data.User = UserCreate.user;
              store.writeQuery({query: USER_CURRENT, data})
            },
            optimisticResponse: {
              __typename: 'Mutation',
              UserCreate: {
                __typename: 'UserCreatePayload',
                user: {
                  __typename: 'User',
                  id: null,
                  username: username,
                }
              }
            }
          })
        },

        login() {
          // save the username and password in case of an error
          const username = this.username;
          const password = this.password;
          // clear things early to make the UI feel snappy
          this.username = '';
          this.password = '';

          this.$apollo.mutate({
            mutation: LOGIN_MUTATION,
            variables: {
              username: username,
              password: password,
            },
            update: (store, { data: { LoginMutation }}) => {
              const data = store.readQuery({query: USER_CURRENT});
              data.User = LoginMutation.user;
              store.writeQuery({query: USER_CURRENT, data})
            },
            refetchQueries: [
              {query: PASTES_ALL}
            ],
          })
        },

        logout() {
          this.$apollo.mutate({
            mutation: LOGOUT_MUTATION,
            update: (store) => {
              store.writeQuery({query: USER_CURRENT, data: {User: null}})
            },
            refetchQueries: [
              {query: PASTES_ALL}
            ],
          })
        },
      },

      apollo: {
        Pastes: PASTES_ALL,
        User: USER_CURRENT,
      }
    }
</script>