<div class="mb-sm-5 detail-page-top-navi {% if show_backlink == 'false' %}d-none{% else %}d-flex{% endif %} justify-content-between align-items-center">
  {% if back_link is not null %}
  <div>
    <a href="{{back_link}}" role="button" class="btn btn-primary"><i class="fas fa-chevron-left"></i> Zurück</a>
  </div>
  {% endif %}
  <div>
    <h1 class="mb-0">{{heading}}</h1>
  </div>
  <div>
    <a role="button" class="btn btn-primary invisible"> <i class="fas fa-chevron-left"></i> Zurück</a>
  </div>
</div>
 <div id="vue-app">
    <p>
      <button class="btn btn-secondary" v-bind:class="{ 'btn-info': mode=='inbox' }"  v-on:click="getInbox">Eingang</button>
      <button class="btn btn-secondary" v-bind:class="{ 'btn-info': mode=='outbox' }" v-on:click="getOutbox">Gesendet</button>
      <button class="btn btn-secondary" v-if="singleCommunication" v-bind:class="{ 'btn-info': mode=='history' }" v-on:click="getHistory">Verlauf</button>
      <button class="btn float-right btn-primary" v-on:click="answerto=null,type=null;subject='',validatedInput=false;compose=true">Neue Nachricht</button>
    </p>
    <template>
      <section v-if="errored">
        <p>Tut uns leid, aber momentan können keine Nachrichten abgerufen werden. Bitte versuchen Sie es später noch einmal.</p>
      </section>
    
      <section v-else>
        <div class="msg-loading" v-if="loading"><i class="fas fa-spinner"></i></div>
        <div v-else>
          <div class="history" v-if="mode=='history'">
             <div
              v-for="message in messages"
              class="bubble"
              v-bind:class="{  'inbox': (message.to_id === myid) }"
              
              >  
                <div class="title" >%{ message.title }</div>
                <div class="copy" v-html="message.content"></div>
                <div class="date" >%{ formatDate(message.date) }</div>
            </div>
          </div>
          <table class="table table-bordered msg-table" v-if="sortedMessages.length > 0">
            <thead>
              <tr>
                
                <th v-on:click="sort('sender')" v-bind:class="{ 'sorted-on': currentSort=='sender' }"  scope="col">%{ mode === 'inbox' ? 'Absender':'Empfänger' }</th>
                <th v-on:click="sort('title')" v-bind:class="{ 'sorted-on': currentSort=='title' }" scope="col">Betreff</th>
                <th v-on:click="sort('date')" v-bind:class="{ 'sorted-on': currentSort=='date' }" scope="col">Datum</th>
                <th v-if="mode != 'outbox'" v-on:click="sort('type_flag')" v-bind:class="{ 'sorted-on': currentSort=='type_flag' }" scope="col">Typ</th>
              </tr>
            </thead>
            <tbody>
              <tr
              v-for="message in sortedMessages"
              class="message table"
              v-bind:class="{  'info': (message.read_at === null) }"
              v-on:click="showMessage(message)"
              >
              
                <td >%{ message.sender }</td>
                <td >%{ message.title }</td>
                <td >%{ formatDate(message.date) }</td>
                <td v-if="mode != 'outbox'" v-bind:class="{ 'message-icon': mode == 'inbox' }"><span v-if="message.type_flag=='ask_for_feedback'"><i class="fas fa-bell"></i></span><span v-else><i class="far fa-envelope"></i></span></td>
              </tr>
            </tbody>
          </table>
          <div v-else class="alert alert-info" role="alert">
            <h5><i class="fas fa-info-circle"></i>&nbsp;Hinweis</h5>
            <p class="mb-0">
              Es sind keine Nachrichten zur Anzeige vorhanden.
            </p>
          </div>
        <div>
      </section>
    </template>
    <section v-if="message">
      <div class="overlay">
        <div class="content card panel panel-default center-block">
                <div class="modal-body">
                    <mail-reader v-bind:entry="message"></mail-reader>
                </div>
                <div class="modal-footer">
                    <button class="btn  btn-secondary" v-on:click="type=null;message=null">Schließen</button>
                    <button class="btn btn-primary float-right" v-if="mode=='inbox'" v-on:click="replyToMessage()">%{ message.type_flag==='ask_for_feedback' ? 'Feedback schreiben' : 'Antworten' }</button>
                </div>
      </div>
    </section>
    <section v-if="compose">
      <div class="overlay">
        <div class="content card card-default email-composer center-block">
          <form ref="mailform" v-on:submit.prevent="submitMessage()">
              <div class="modal-header">
                  <div class="card-heading"><h3>%{ type==='feedback' ? 'Feedback' : 'Neue Nachricht' }</h3></div>
              </div>
              <div class="modal-body card-body composer-panel-body">   
                  <div class="form-group">
                    <section v-if="getRecipientById(userid)!==null">
                        <h4>Empfänger: %{ getRecipientById(userid).name }</h4>
                    </section>
                    <section v-else-if="getRecipientById(answerto)!==null">
                        <h4>Empfänger: %{ getRecipientById(answerto).name }</h4>
                    </section>
                    <section v-else>
                      <h4>Empfänger:</h4>
                        <select ref="selectRecipient">
                            <option v-for="recipient in recipients" v-bind:value="recipient.id">%{ recipient.name }</option>
                        </select>
                    </section>
                  </div>

                  <div class="form-group">
                      <input class="form-control" ref="subject" type="text" v-on:change="validateForm()" v-on:keyup="validateForm()" placeholder="Betreff" name="subject" v-model="subject"/>
                  </div>
                  <div class="form-group">
                    <!--<textarea class="form-control" ref="message" placeholder="Nachricht" name="message" v-on:change="validateForm()" v-on:keyup="validateForm()" style="max-height:none"></textarea>-->
                    <div class="textarea" ref="message" contenteditable v-on:input="onInput" ></div>
                  </div> 
          
                </div>
              <div class="modal-footer">
                  <div class="formats">
                      <div class="btn btn-secondary" v-on:click.stop="format('bold')"><i class="fas fa-bold"></i></div>
                      <div class="btn btn-secondary" v-on:click.stop="format('italic')"><i class="fas fa-italic"></i></div>
                      <div class="btn btn-secondary" v-on:click.stop="format('underline')"><i class="fas fa-underline"></i></div>
                  </div>
                  <div class="btn btn-secondary" v-on:click.stop="closeOverlay">Abbrechen</div>
                  <div class="btn btn-primary float-right" v-bind:class="{ 'disabled': validatedInput===false }" v-on:click.prevent="submitMessage()">Senden</div>
              </div>
          </form>
        </div>
      </div>
    </section>
</div>

<style>
    .overlay{
      z-index:2000;
      position: fixed;
      width: 100%;
      height: 100%;
      background: rgba(0,0,0,0.6);
      top:0;
      left:0;
      display: flex;
      align-items: center;
      box-sizing: border-box;
    }
    .textarea{
      display: block;
      width: 100%;
      padding: 6px 12px;
      font-size: 1.2em !important;
      font-weight: 400;
      line-height: 1.5;
      color: #495057;
      background-color: #fff;
      background-clip: padding-box;
      border: 1px solid #ced4da;
      border-radius: .25rem;
      height:100%;
    }
    .formats{
      flex-grow:1;
    }
    .overlay .content{
      box-sizing: border-box;
      width: 60%; 
      margin: 0 auto;
      height: 80%;
      background: #ffffff;
      position: relative;
    }

    .overlay input, .overlay textarea{
      width: 100%;
      /* border-radius: 0;
      border: 1px solid #cccccc; */
    }

    .overlay .mail-reader{
      white-space: pre-line;
      overflow-y: auto;
      height: 100%;
    }

    .overlay .modal-footer{
      bottom:0;
      left:0;
      right: 0;
      height: 65px;
    }

    .content form {
      height: 100%;
    }

    .content .modal-body {
      display: flex;
      flex-direction: column;
      height: calc(100% - 130px);
      overflow-y: auto;
    }

    .content form .modal-body div.form-group:last-child {
      flex: 2;
    }

    th{
      -webkit-user-select: none; /* Safari 3.1+ */
      -moz-user-select: none; /* Firefox 2+ */
      -ms-user-select: none; /* IE 10+ */
      user-select: none; /* Standard syntax */
      cursor: ns-resize;
    }

    th.sorted-on{
      text-decoration: underline;
    }

    .email-composer textarea{
      height: 100%;
      max-height: none;
    }

    .email-composer .panel-heading{
      padding: 15px 20px 0 16px;
    }

    .email-composer input, .email-composer textarea{
      transition: border 0.5s;
    }

    .email-composer input:focus, .email-composer textarea:focus{
      outline: none;
      border: 1px solid #333333;
    }

    .btn-default.disabled{
      opacity:0.5;
    }

    .bubble{
      padding: 10px;
      /* color: #ffffff; */
      color: #000000;
      margin-bottom: 10px;
      margin-left: 50px;
      /* background: #4A90E2; */
      background: #F2F2F2; /*$color-light-grey*/
      border-radius: 5px;
    }

    .bubble.inbox{
      color: #000000;
      margin-left: 0px;
      margin-right: 50px;
      background: #cccccc;
    }

    .bubble .date, .bubble .title{
      font-size: 75%;
    }

     .bubble .date{
      margin-top: 0.5em;
    }

    .bubble .copy{
      white-space: pre-line;
    }

    .message-icon {
      vertical-align: middle !important;
      text-align: center;
      font-size: 20px;
    }

    .msg-table tbody {
    cursor: pointer;
    }

   

</style>

<script>
  var ajax_url = '{{ ajaxurl }}';
  var userid = '{{ userid }}';
  var myid = '{{ myid }}';
  var backtoorigin = '{{ backtoorigin }}';
  var refurl = '{{refurl | raw}}';
</script>

<script src="{{ vuejs_script_path }}"></script>
<script src="{{ axios_script_path }}"></script>
<script>


  Vue.component('mail-reader', {
      delimiters: ['%{', '}'],
       data() {
        return {
          loading: true,
          errored: false,
          message: null,
          userid: null,
        }
      },
      props: ['entry'],
      template: `<div class="mail-reader">
                  <div v-if="loading">Nachricht wird geladen...</div>
                  <div v-else>
                      <h1>%{message.title}</h1>
                      <div v-html="message.content"></div>
                  </div>
                </div>
                `,
      mounted() {
          let fd = new FormData();
          fd.append("action", "mailbox");
          fd.append("mailbox-action", "get-message");
          fd.append("message-id", this.entry.id );
          axios({
            method: 'post',
            url: ajax_url,
            data: fd,
            config: { headers: { 'Content-Type': 'multipart/form-data' } }
          })
            .then(response => {
              this.message = response.data;
              console.log(response.data);
            })
            .catch(error => {
              console.log(error)
              this.errored = true
            })
            .finally(() => this.loading = false)
    }
  })

  new Vue({
  delimiters :['%{', '}'],
  el: '#vue-app',
  data () {
    return {
      messages: null,
      loading: true,
      errored: false,
      message: null,
      compose: null,
      recipients: null,
      userid: (userid !=='' ? userid : null),
      myid: (myid !=='' ? myid : null),
      answerto: null,
      subject:'',
      lektionid:null,
      type: null,
      mode: 'inbox',
      currentSort:'date',
      currentSortDir:'desc',
      validatedInput: false,
    }
  },
  computed:{
    sortedMessages:function() {
      return this.messages.sort((a,b) => {
        let modifier = 1;
        if(this.currentSortDir === 'desc') modifier = -1;
        if(a[this.currentSort] < b[this.currentSort]) return -1 * modifier;
        if(a[this.currentSort] > b[this.currentSort]) return 1 * modifier;
        return 0;
      });
    },
    singleCommunication:function(){
      if(this.userid!==null){
        return true;
      }
      if(this.recipients!==null && this.recipients.length==1){
        return true;
      }
      return false;
    }
  },
  methods: {
    formatDate(str){
          var date = str.split(' ')[0];
          var time = str.split(' ')[1];
          var dp=date.split('-');
          var tp=time.split(':');
          return dp[2]+'.'+dp[1]+'.'+dp[0] +" " + tp[0] +':'+tp[1]+' Uhr'

    },
    sort:function(s) {
      //if s == current sort, reverse
      if(s === this.currentSort) {
        this.currentSortDir = this.currentSortDir==='asc'?'desc':'asc';
      }
      this.currentSort = s;
    },
    onInput(e) {
      this.validateForm();
    },
    format(format){
      document.execCommand(format);
    },
    validateForm(){
      if(this.$refs.subject.value !=="" && this.$refs.message.innerText !==""){
        this.validatedInput=true;
      }else{
        this.validatedInput=false;
      }
    },
    replyToMessage (){
      this.answerto=this.message.from_id;  
      if(this.message.type_flag=='ask_for_feedback'){
        this.type='feedback';
        this.lektionid=this.message.lektion_id;
        if(this.message.title.match(/"(.*)"/).length>0){
          this.subject='Feedback - ' + this.message.title.match(/"(.*)"/)[0];
        }else{
          this.subject='Feedback' ;
        }
        
      }else{
        this.subject='Re: ' + this.message.title;
      }
      this.compose=true;
      this.message=null;
      
    },
    submitMessage (){
  
      this.validateForm();
      if(!this.validatedInput){
        return;
      }

      let fd = new FormData(this.$refs.mailform);
      fd.append("message",this.$refs.message.innerHTML);
      fd.append("action", "mailbox");
      fd.append("mailbox-action", this.type=='feedback' ? 'feedback':'send');
      fd.append("lektionid", this.lektionid);
      fd.append("userid", this.userid);
     
      if(this.userid){
        fd.append("recipient", this.userid);
      }else if(this.answerto){
        fd.append("recipient", this.answerto);
      }else{
        fd.append("recipient", this.$refs.selectRecipient.value );
      }
      
      axios({
          method: 'post',
          url: ajax_url,
          data: fd,
          config: { headers: {'Content-Type': 'multipart/form-data' }}
      }).then(response => {
        this.compose = false;
        if(backtoorigin == true) {
          window.location.href = refurl;
        } else {
          if(this.mode=='outbox' || this.mode=='history'){
            this.getMessages(this.mode);
          }
        }
      })
    },
    showMessage (message){
        if((this.mode=='inbox')){ 
          if(! message.read_at){
            console.log("first Read",message.from_id);
            var b=document.querySelector('.mailbox-count-bubble');
            if(b){
              var count=parseInt(b.innerHTML);
              count --;
              b.innerHTML=count.toString();
              if(count<=0){
                b.parentElement.removeChild(b);
              }
            }
          }
          message.read_at=new Date().getTime(); 
        }
        this.message=message;
    },
    getInbox(){
      this.mode='inbox';
      this.getMessages("inbox");
    },
    getOutbox(){
      this.mode='outbox';
      this.getMessages("outbox");
    },
    getHistory(){
      this.mode='history';
      this.getMessages("history");
    },
    getMessages(mode){
      console.log('get Messages', this.mode)
      this.messages=[];
      this.loading=true;
      let fd = new FormData();
      fd.append("action", "mailbox");
      fd.append("mailbox-action", mode);
      fd.append("userid", this.userid );
      axios({
          method: 'post',
          url: ajax_url ,
          data: fd,
          config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
      .then(response => {
        console.log(response);
        this.messages = response.data.result;
      })
      .catch(error => {
        console.log(error)
        this.errored = true
      })
      .finally(() => this.loading = false)
    },
    getRecipients(mode){

      let fd = new FormData();
      fd.append("action", "mailbox");
      fd.append("mailbox-action", "get-users");
      fd.append("userid", this.userid );
      axios({
          method: 'post',
          url: ajax_url ,
          data: fd,
          config: { headers: {'Content-Type': 'multipart/form-data' }}
      })
      .then(response => {
        this.recipients = response.data;
      })
    },
    getRecipientById(id){
      if(! this.recipients){
        return "";
      }
      for(var i=0;i<this.recipients.length;i++){
        if(this.recipients[i].id==id){
          return this.recipients[i];
        }
      }
      return null;
    },
    closeOverlay() {
      this.compose=false;
      if(backtoorigin == true) {
        window.location.href = refurl;
      }
    }
  },
  created()
  {
    let uri = window.location.href.split('?');
    if (uri.length == 2)
    {
      let vars = uri[1].split('&');
      let getVars = {};
      let tmp = '';
      vars.forEach(function(v){
        tmp = v.split('=');
        if(tmp.length == 2)
        getVars[tmp[0]] = decodeURIComponent(tmp[1]);
      });
      if(getVars.action==="userlist"){
        this.userid=getVars.user;
        this.mode='outbox';
        if(getVars.type=="feedback"){
          this.compose = true;
          this.lektionid= getVars.lektion;
          this.type = getVars.type; 
          this.subject = getVars.subject;
        }else if(getVars.type=="message"){
          this.compose = true;
          this.type = getVars.type; 
        }
      }
    }
  },
  mounted () {
      console.log("mounted", this.mode)
      if(this.mode=='inbox'){
        this.getInbox();
      }else if(this.mode=='outbox'){
        this.getOutbox();
      }else{
        this.getHistory();
      }
      
      this.getRecipients();
  }
  
})

</script>




