<template>
  <div id="FileSharing">
    
      <!-- breadcrumb -->
      <nav class="text-sm font-semibold mb-6" aria-label="Breadcrumb">
        <ol class="list-none p-0 inline-flex">
          <li class="flex items-center text-blue-500">
            <a href="#" class="text-gray-700">Main</a>
            <svg class="fill-current w-3 h-3 mx-3" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 512"><path d="M285.476 272.971L91.132 467.314c-9.373 9.373-24.569 9.373-33.941 0l-22.667-22.667c-9.357-9.357-9.375-24.522-.04-33.901L188.505 256 34.484 101.255c-9.335-9.379-9.317-24.544.04-33.901l22.667-22.667c9.373-9.373 24.569-9.373 33.941 0L285.475 239.03c9.373 9.372 9.373 24.568.001 33.941z"/></svg>
          </li>
          <li class="flex items-center">
            <a href="#" class="text-gray-600">WAMPAC Drive</a>
          </li>
        </ol>
      </nav>
      <!-- breadcrumb end -->
        <div class="flex flex-wrap -mx-3 mb-5">
        <div class="w-1/4 l:w-1/4 px-3">
                <div class="w-full bg-white border text-blue-400 rounded-lg flex items-center p-6 mb-6 xl:mb-0">
                  <svg class="w-16 h-16 fill-current mr-4 hidden lg:block" viewBox="0 0 20 20">
                    <path d="M14.999,8.543c0,0.229-0.188,0.417-0.416,0.417H5.417C5.187,8.959,5,8.772,5,8.543s0.188-0.417,0.417-0.417h9.167C14.812,8.126,14.999,8.314,14.999,8.543 M12.037,10.213H5.417C5.187,10.213,5,10.4,5,10.63c0,0.229,0.188,0.416,0.417,0.416h6.621c0.229,0,0.416-0.188,0.416-0.416C12.453,10.4,12.266,10.213,12.037,10.213 M14.583,6.046H5.417C5.187,6.046,5,6.233,5,6.463c0,0.229,0.188,0.417,0.417,0.417h9.167c0.229,0,0.416-0.188,0.416-0.417C14.999,6.233,14.812,6.046,14.583,6.046 M17.916,3.542v10c0,0.229-0.188,0.417-0.417,0.417H9.373l-2.829,2.796c-0.117,0.116-0.71,0.297-0.71-0.296v-2.5H2.5c-0.229,0-0.417-0.188-0.417-0.417v-10c0-0.229,0.188-0.417,0.417-0.417h15C17.729,3.126,17.916,3.313,17.916,3.542 M17.083,3.959H2.917v9.167H6.25c0.229,0,0.417,0.187,0.417,0.416v1.919l2.242-2.215c0.079-0.077,0.184-0.12,0.294-0.12h7.881V3.959z"></path>
                  </svg>
                  <div class="text-gray-700">
                    <p class="font-semibold text-3xl">{{TokenCount}}</p>
                    <p>Token Balance <span class="px-2"></span></p>
                  </div>
                  </div>
                </div>
              </div> 

        
      <div class="lg:flex justify-between items-center mb-6">
        <p class="text-2xl font-semibold mb-2 lg:mb-0">WAMPAC Drive &nbsp;-<span>
          <li class="border-blue-400 bg-blue-400 rounded-full inline-block -ml-3">
          <router-link to="" class="text-m rounded-full h-8 w-8 flex items-center justify-center overflow-hidden text-white">
              {{filesShared}}
          </router-link>
      </li>
      </span>
      </p> 
            <router-link to="/dashboard/upload-file"><button class="bg-blue-500 hover:bg-blue-600 focus:outline-none rounded-lg px-6 py-2 text-white font-semibold shadow">Create New Contract</button></router-link>
      </div>
      <p>Update any files shared with other nodes in the network. </p>
      
      <br>
      <p v-if="filesShared==0">No Shared Files</p>
      <div v-if="filesShared!=0" class="lg:flex justify-between items-center mb-6">
        <table class="tables table-fixed">
        <thead>
          <tr>
            <th class="w-1/4 ...">File Name</th>
            <th class="w-1/4 ..."></th>
            <th class="w-1/4 ..."></th>
          </tr>
        </thead>
        <tbody>
          <tr class="bg-blue-100" v-for="fileList in fileList" :key="fileList">
            <td>{{ fileList }} </td>
            <td>  <button v-on:click="detailsPopup(fileList)" class="bg-blue-100 hover:bg-blue-500 focus:outline-none rounded-sm px-6 py-2 text-black font-semibold shadow">Details</button> </td>
            <td> <button v-on:click="toggleUpdate(fileList)" class="bg-blue-100 hover:bg-blue-500 focus:outline-none rounded-sm px-6 py-2 text-black font-semibold shadow">Update</button> </td>
          </tr>
        </tbody>
      </table>
      </div>
      <modal name="file-update-modal">
      <div v-if=showPopup class="w-full bg-white border rounded-lg p-4">

      <p class="text-l font-semibold mb-4">File Token:
      <span class="text-sm font-normal mb-4">{{fileUpdate.fileHash}}</span></p>
      <p class="text-l font-semibold mb-4">Current Hash:
      <span class="text-sm font-normal mb-4">{{fileUpdate.token}}</span> </p>
      <div class="w-full xl:w-1/2 px-3">
        <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
        <span class="p-40" v-if="showUpdating">
        <Progress strokeColor="#516091" value="87">
          <template v-slot:footer>
            <b>Updating Selected File, Please wait..</b>
          </template>
        </Progress>
        </span>
        </div>
      </div>
      <div v-if="!showUpdating && showPopup" class="w-full xl:w-1/2 px-3 py-10">
      <button v-on:click="launchFileContract(fileUpdate.token), fetchingStats = true" class="center bg-blue-500 hover:bg-blue-600 focus:outline-none rounded-sm px-2 py-2 text-white font-semibold shadow">Update</button>
      </div>
      <div class="py-20">
      <p class="text-gray-700 font-semibold text-xl center">{{updateResponse}}</p>
      </div>
      
      </modal>
      <modal name="file-info-modal">
        <div class="w-full bg-white border rounded-lg p-4">
        <p class="text-gray-700 font-semibold text-3xl">{{fileDetail.fileName}}</p>
        <p class="text-gray-700 font-semibold text-sm">Token: {{fileDetail.token }}</p>
        <p class="text-gray-700 font-semibold text-sm">File Hash: {{fileDetail.fileHash }}</p>
        <p class="text-gray-700 font-semibold text-sm">Status: {{fileDetail.status }}</p>
        <p class="text-black-700 font-semibold text-l">Contract Data</p>
        <div class="w-full bg-white border rounded-lg p-4">
          <div class="w-full bg-gray-100 border rounded-lg flex justify-between items-center px-1 py-2">
              <div>
                <ul>
                <li v-for="data in fileDetail.contractData" :key="data">
                <div class="did font-semibold text-xs"><span class="text-black-500 font-normal text-xs"> {{data.did}}</span> {{ data.ip }} <span class="text-red-500 font-semibold text-sm"> {{ data.writeCount }}</span></div>
                <hr>
              </li>
              </ul>
              </div>
          </div>
        </div>
        <p class="text-blue-700 font-semibold text-xl">You accessed this file {{fileDetail.accessCount }} times</p>
      </div>
    </modal>
  </div>
</template>

<script>
import Vue from 'vue'
import axios from 'axios'
import VModal from 'vue-js-modal'
import Progress from 'easy-circular-progress'

Vue.use(VModal, {
  dynamicDefaults: {
    draggable: true,
    resizable: true,
    height: 'auto'
  }
})

export default {
  name: 'FileSharing',
  data() {
    return {
      filesShared: 0,
      TokenCount: 0,
      open: false,
      fileToken: "",
      fileDetail: {},
      fileUpdate: {},
      showPopup: false,
      showUpdating: false,
      fileList: [],
      updateResponse: '',
      newFile: {}
    }
  },
  components: {
    Progress
  },

  methods: {

    getTokenCount: function () {
    
      console.log("loading contactsOnline")

      axios.get('http://localhost:1898/getTokenCount')
    .then((response) => {
      this.TokenCount = response.data.data

    })
    .catch(function (error) {
      console.log(error);
    });
    },

    thumbUrlOld (file) {
      return file.myThumbUrlProperty
    },
    thumbUrlNew (file) {
      return file.myThumbUrlProperty
    },
    // onChangeNew (file) {
    //   console.log('New File selected!')
    //   if (file) {
    //     this.newFile = file
    //     console.log("uploading file")
    //   } else {
    //     console.log('FileReader API not supported: use the <form>, please!')
    //   }
    // },

    handleFileUpload(){
    this.newFile = this.$refs.file.files[0];
  },

    detailsPopup: function (token) {
      this.$modal.show('file-info-modal');
      this.open = true
      console.log(token)
      const formData = new FormData()
      formData.append('fileName', token)


      console.log("loading file details")

      axios.post('http://localhost:1898/getSharedFileDetails', formData,{
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then((response) => {

      console.log(response);
      this.fileDetail = response.data.data.response
      console.log("printing result")
      console.log(this.fileDetail.Status)

    })
    .catch(function (error) {
      console.log(error);
    });
    },

    toggleUpdate: function (token) {
      this.updateResponse = ''
      this.showUpdating = false
      this.$modal.show('file-update-modal');
      this.showPopup = true
      this.fileToken = token
      // if(token == 'close'){
      //   this.showPopup = !this.showPopup
      // }
      console.log(token)

      const formData = new FormData()
      formData.append('fileName', token)

      axios.post('http://localhost:1898/getSharedFileMetaData', formData,{
      headers: {
        'Content-Type': 'multipart/form-data'
      }
      })
      .then((response) => {

        console.log(response);
        this.fileUpdate = response.data.data.response
        // this.$modal.hide('file-update-modal');

      })
      .catch(function (error) {
        console.log(error);
      });
    },
    

    launchFileContract: function (token) {
      // this.open = false
      this.showUpdating = true
      this.updateResponse = ''
      const formData = new FormData()
      formData.append('newfile', this.newFile)
      formData.append('token', token)

      console.log("loading launchFileContract")

      axios.post('http://localhost:1898/update', formData,{
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    .then((response) => {
      this.showUpdating = false
      this.updateResponse = response.data.data.response
      this.newFile = ''
      this.showPopup = false
      // this.open = false
      console.log(this.responseDID)
     // TODO: GOTO HOME AND SHOW LOADER

    })
    .catch(function (error) {
      console.log(error);
    });
    },

    checkStatus: function () {
    
      console.log("loading DID exists")

      axios.get('http://localhost:1898/checkDidExists')
    .then((response) => {

      console.log(response);
      if(response.data.data.payload == 'Failure'){
        console.log("moving to create DID")
        this.$router.push({path: '/create-new-DID'})
        return;
      } else {
        console.log("loading DID verified")
          axios.get('http://localhost:1898/checkDidVerified')
          .then((response) => {
            this.isVerified = response.data.data.payload
            console.log(response);
            if(response.data.data.payload == 'Failure'){
              console.log("moving to create DID [check]")
              this.$router.push({path: '/verification'})
              return;
            }
          })
          .catch(function (error) {
            console.log(error);
            this.$router.push({path: '/verification'})
            return;
          });
      }
    })
    .catch(function (error) {
      console.log(error);
      this.$router.push({path: '/create-new-DID'})
      return;
    });

    


    axios.get('http://localhost:1898/checkRole')
    .then((response) => {

      console.log(response);
      // this.myRole = response.data.data.payload
    })
    .catch(function (error) {
      console.log(error);
      // this.$router.push({path: '/create-new-DID'})
    });
    },

    getFiles: function () {
    
      console.log("loading list of Files")

      axios.get('http://localhost:1898/getSharedFiles')
    .then((response) => {
      this.fileList = response.data.data.response
      this.filesShared = response.data.data.response.length
      
    })
    .catch(function (error) {
      console.log(error);
    });
    },

    getToken: function () {

      axios.get('http://localhost:1898/requestTokens')
    .then((response) => {
      if(response.data.data.payload == 'Failure') {
        this.$router.push({path: '/dashboard/home'})
      }
      
    })
    .catch(function (error) {
      console.log(error);
    });
    },
    
  },
  beforeMount() {
      this.getToken()
      this.checkStatus()
      this.getFiles()
      this.getTokenCount()
  }

}
</script>
  
<style>

.center{
  text-align: center;
}
.modalBefore {
  top:-300px;
  margin:auto;
}

.modalAfter {
  top:200px;
}

</style>