<template>
  <div class="row">
<div>
  <b-modal header-bg-variant="success" header-text-variant="light" hide-footer id="messagesModal" scrollable :title="modalTitle">


<h5>Compose new comment</h5>
<b-form v-on:submit.prevent v-on:submit="submitMessage(backupID)" class="text-right mb-4">
  <b-form-textarea
      required
      id="textarea-state"
      v-model="form.messagetext"
      :state="form.messagetext.length >= 10"
      placeholder="Enter at least 10 characters"
      rows="3"
    ></b-form-textarea>
 <b-button class="mt-2" type="submit" variant="success">Submit</b-button>
 </b-form>


   <b-card no-body bg-variant="light" class="mb-4" v-for="message in backupMessages" v-bind:key="message.id">
    <b-card-header class="pl-2 d-flex justify-content-between align-items-center">
<span><b-avatar variant="primary" size="2rem" :text="message.owner | initials"></b-avatar>&nbsp;&nbsp;{{message.owner | fullname}}</span>
<span>{{message.created_at}}</span>
    </b-card-header>
    <b-card-body>
      <b-card-text>
{{message.comment}}
      </b-card-text>
    </b-card-body>
  </b-card>


  </b-modal>
</div>
    <div class="col-xs-12 col-md-3 offset-md-9 mb-3">
<input class="form-control" type="search" placeholder="Search" v-model="searchTerm" aria-label="Search">
    </div>
    <div class="col table-responsive">
      <ul class="nav nav-tabs">

      <li class="nav-item pr-1">
        <a class="nav-link" href="#/remaining" :class="{ active: visibility == 'remaining' }">
          Open &nbsp;&nbsp;<span class="badge badge-light">{{ remaining }}</span>
      </a>
      </li>

      <li class="nav-item pr-1">
        <a class="nav-link" href="#/inprogress" :class="{ active: visibility == 'inprogress' }">
          In Progress &nbsp;&nbsp;<span class="badge badge-light">{{ inprogress }}</span>
      </a>
      </li>

      <li class="nav-item pr-1">
        <a class="nav-link" href="#/resolved" :class="{ active: visibility == 'resolved' }">
          Resolved &nbsp;&nbsp;<span class="badge badge-light">{{ resolved }}</span>
      </a>
      </li>

</ul>
      <table class="table table-bordered table-hover shadow">
        <thead class="thead-dark">
          <tr>
            <th>Hostname</th>
            <th class="text-center">Hardware Node</th>
            <th class="text-center">Timestamp</th>
            <th class="text-center">Status</th>
            <th class="text-center">Assigned To | Resolved By</th>
            <th class="text-center">Resolved On</th>
            <th class="text-center">Actions</th>
          </tr>
        </thead>
        <tbody>
           <tr class="loader">
            <td colspan="100%" class="text-center">
          <b-spinner style="width: 3rem; height: 3rem;" variant="primary" type="grow" label="Loading Data"></b-spinner>
        </td>
        </tr>
          <tr v-for="backup in filteredBackups" v-bind:key="backup.id">
            <td class="align-middle">{{backup.hostname}}</td>
            <td class="text-center align-middle">{{backup.node}}</td>
            <td class="text-center align-middle">{{backup.timestamp}}</td>
            <td class="text-center align-middle" v-if="backup.status === 0"><h5 class="mb-0"><span class="badge badge-danger">Open</span></h5></td>
            <td class="text-center align-middle" v-else-if="backup.status === 1"><h5 class="mb-0"><span class="badge badge-success">Resolved</span></h5></td>
            <td class="text-center align-middle" v-else-if="backup.status === 2"><h5 class="mb-0"><span class="badge badge-warning">In Progress</span></h5></td>
            <td class="text-center align-middle">{{backup | fullnameBackup }}</td>
            <td class="text-center align-middle">{{backup.completed_at}}</td>
            <td class="text-center align-middle">
              <div class="row">
              <div class="col pr-1 pl-1 ml-2" v-if="backup.status === 0">
              <button class="btn btn-outline-primary btn-block" type="submit" @click="setassign(backup.id)">Assign to me</button>
            </div>
            <div class="col pr-1 pl-1 ml-2" v-if="backup.status === 2">
              <button class="btn btn-warning btn-block" type="submit" @click="setassign(backup.id)">Unassign</button>
            </div>
            <div class="col pr-1 pl-1 ml-2">
              <button v-if="backup.status === 0 || backup.status === 2" type="submit" class="btn btn-outline-success btn-block" @click="setstatus(backup.id)">Resolved</button>
              <button v-else-if="backup.status === 1 || backup.status === 2" type="submit" class="btn btn-danger btn-block" @click="setstatus(backup.id)">Mark as open</button>
            </div>
<b-button @click="showMessages(backup.id)" class="ml-2 mr-3"><i class="fas fa-comments"></i> 
  <span v-if="backup.comments_count > 0" class="badge badge-light">{{backup.comments_count}}</span></b-button>
          </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script>
  var filters = {
    // all: function(backups,searchTerm) {
    //   return backups.filter(function(backup) {
    //     return backup.hostname.toLowerCase().includes(searchTerm) ||
    //      backup.node.toLowerCase().includes(searchTerm) ||
    //      backup.timestamp.toLowerCase().includes(searchTerm);
    //   });
    // },
    //   ongoing: function(backups,searchTerm) {
    //   return backups.filter(function(backup) {
    //     if(backup.status === 0 || backup.status === 2) { 
    //    return backup.hostname.toLowerCase().includes(searchTerm) ||
    //      backup.node.toLowerCase().includes(searchTerm) ||
    //      backup.timestamp.toLowerCase().includes(searchTerm);
    //    };
    //   });
    // },
    remaining: function(backups,searchTerm) {
      return backups.filter(function(backup) {
        if(backup.status === 0) { 
          if(backup.timestamp === null){
       return backup.hostname.toLowerCase().includes(searchTerm) ||
         backup.node.toLowerCase().includes(searchTerm);
       }else {
               return backup.hostname.toLowerCase().includes(searchTerm) ||
         backup.node.toLowerCase().includes(searchTerm) ||
         backup.timestamp.toLowerCase().includes(searchTerm);
       }
       };
      });
    },
    resolved: function(backups,searchTerm) {
      return backups.filter(function(backup) {
        if(backup.status === 1) {
                    if(backup.timestamp === null){
        return backup.hostname.toLowerCase().includes(searchTerm) ||
         backup.node.toLowerCase().includes(searchTerm) ||
         backup.solver.firstname.toLowerCase().includes(searchTerm) ||
         backup.solver.lastname.toLowerCase().includes(searchTerm) ||
         backup.completed_at.toLowerCase().includes(searchTerm);
       }else {
         backup.node.toLowerCase().includes(searchTerm) ||
         backup.solver.firstname.toLowerCase().includes(searchTerm) ||
         backup.solver.lastname.toLowerCase().includes(searchTerm) ||
         backup.completed_at.toLowerCase().includes(searchTerm) ||
         backup.timestamp.toLowerCase().includes(searchTerm);
       }
       };
      });
    },
    inprogress: function(backups,searchTerm) {
      return backups.filter(function(backup) {
        if(backup.status === 2) {
                              if(backup.timestamp === null){
        return backup.hostname.toLowerCase().includes(searchTerm) ||
         backup.node.toLowerCase().includes(searchTerm) ||
         backup.assignee.firstname.toLowerCase().includes(searchTerm) ||
         backup.assignee.lastname.toLowerCase().includes(searchTerm);
       } else {
                return backup.hostname.toLowerCase().includes(searchTerm) ||
         backup.node.toLowerCase().includes(searchTerm) ||
         backup.assignee.firstname.toLowerCase().includes(searchTerm) ||
         backup.assignee.lastname.toLowerCase().includes(searchTerm) ||
         backup.timestamp.toLowerCase().includes(searchTerm);
       }
       };
      });
    }
  };
  export default {
    mounted() {

      this.fetchData();
      window.addEventListener("hashchange", this.onHashChange);
      this.onHashChange();
    },
    data () {
      return {
        backupMessages: [],
        backupID: '',
        modalTitle: 'test',
        searchTerm: '',
        failedBackups: [],
        backid:'',
        visibility: 'remaining',
        toastsCount: 0,
        form: {
         messagetext: '', 
        }
      }
    },
    filters: {
    fullnameBackup: function(backup) {
        if(backup.assigned && backup.status === 2){
return backup.assignee.firstname+' '+backup.assignee.lastname;
        }
        else if (backup.solvedBy && backup.status === 1) {
          return backup.solver.firstname+' '+backup.solver.lastname;
        }
    },
        fullname: function(message) {
          return message.firstname+' '+message.lastname;
    },
        initials: function(message) {
return message.firstname.substring(0,1)+message.lastname.substring(0,1);
    },
  },
    methods: {
 showMessages(backupid) {

        axios.post('/todo/backups/getcomments',{backupid: backupid})
        .then((response)=>{
          this.backupMessages = response.data.messages;
          this.modalTitle = response.data.hostname + " comments";
          this.$bvModal.show('messagesModal');
          this.backupID = response.data.backupid;
        })
      },
      submitMessage(backupID) {
                axios.post('/todo/backups/postcomment',{backupid: backupID, message: this.form.messagetext})
        .then((response)=>{
            this.form.messagetext = '';
  this.makeToast(true,response.data.message,'success');
  this.showMessages(backupID);
  this.fetchData();
        })
},
onHashChange () {
  this.visibility = window.location.hash.replace(/#\/?/, "");
    if (!filters[this.visibility]) {
      window.location.hash = "";
      this.visibility = "remaining";
    }
  },
      fetchData () {
        axios.get('/todo/backups/data')
        .then((response)=>{
          this.failedBackups = response.data;
          document.querySelector('.loader').style.display = 'none';
        });
      },
      setstatus(backupid){
        axios.post('/todo/backups/setstatus',{backupid: backupid})
        .then((response)=>{
          this.fetchData();
          this.makeToast(true,response.data.message,'secondary');
        })
      },
      setassign(backupid){
        axios.post('/todo/backups/setassign',{backupid: backupid})
        .then((response)=>{
          this.fetchData();
          this.makeToast(true,response.data.message,'secondary');
        })
      }
    },
    computed: {
      filteredBackups: function() {
        return filters[this.visibility](this.failedBackups,this.searchTerm.toLowerCase());
      },
      // ongoing: function() {
      //   return filters.ongoing(this.failedBackups,this.searchTerm.toLowerCase()).length;
      // },
      // all: function() {
      //   return filters.all(this.failedBackups,this.searchTerm.toLowerCase()).length;
      // },
      remaining: function() {
        return filters.remaining(this.failedBackups,this.searchTerm.toLowerCase()).length;
      },
      resolved: function() {
        return filters.resolved(this.failedBackups,this.searchTerm.toLowerCase()).length;
      },
      inprogress: function() {
        return filters.inprogress(this.failedBackups,this.searchTerm.toLowerCase()).length;
      },
    }
  };
</script>