<template>   
    <div> 
         <b-card header="Clients in network">
             <template slot="header">
                <h6 class="mb-0 left">Clients in network</h6>
                <b-btn @click="showNewClient=!showNewClient" variant="success" class="right btn-ssm"  size="sm"> Add new client </b-btn>
                <b-btn @click.stop="resetPeers()" variant="danger" class="right btn-ssm"  size="sm"> Reset tracker peers DB </b-btn>
                
             </template>
            <!-- New Client Form -->
            <b-collapse id="collapseClient" v-model="showNewClient">
                <b-card>
                    <b-form>
                        <b-container class="bv-example-row">
                            <b-row>
                                <b-col>
                                    <b-form-group id="clientAdress"
                                            label="Address"
                                            label-for="clientAdressinput"
                                            description="Enter IP, IP range, FQDM or FQDMS delimited by semicolon.">
                                        <b-form-input id="clientAdressinput" 
                                            v-model="newClient.address" 
                                            type="text" 
                                            placeholder="example: 192.168.1.1-5;localhost;pc-jareknovotny"> </b-form-input>
                                    </b-form-group>
                                </b-col>
                                 <b-col>
                                    <b-form-group id="clientPort"
                                            label="Port"
                                            label-for="clientPortInput"
                                            description="Specify portnumber if it is not default.">
                                        <b-form-input id="clientPortInput" 
                                            v-model="newClient.port" 
                                            type="number" 
                                            placeholder="Port (if not default)"> </b-form-input>
                                    </b-form-group>
                                </b-col>
                            </b-row>
                            <b-row>
                                 <b-col>
                                 <b-form-group id="clientgroupsgr"
                                            label="Groups "
                                            label-for="clientgroupsnew"
                                            description="Editen group names (delimited by semicolon).">
                                            <b-form-input 
                                                id="clientgroupsnew"
                                                v-model="newClient.groupsconcated" 
                                                type="text"> 
                                            </b-form-input>
                                        </b-form-group>
                                </b-col>
                                <b-col>
                                     <b-form-group id="clientLabel"
                                            label="Descriptive Label"
                                            label-for="clientLabelInput"
                                            description="Whatever you want.">
                                        <b-form-input id="clientLabelInput" v-model="newClient.title" type="text" placeholder="Enter label"> </b-form-input>
                                     </b-form-group>
                                </b-col>
                            </b-row>
                            <b-row>
                                <b-col style="text-align: center;">
                                    <b-button variant="primary" @click="onNewClientSubmit">Submit</b-button>
                                    <b-button variant="danger" @click="onNewClientReset">Cancel</b-button>
                                </b-col>
                            </b-row>
                        </b-container>
                    </b-form>
                </b-card>
            </b-collapse>

        <b-table striped hover :items="clients" :fields="clientsfields" :small="true" stacked="md">
            <template slot="groups" slot-scope="row">
                <template v-for="gr in row.item.groups">
                   <b-badge variant="light">{{gr}}</b-badge>
                </template> 
            </template>
            <template slot="last_update" slot-scope="row">
                  <template  v-if="row.item.connected && row.item.torrentCount>0 && row.item.active">
                        <b-progress :max="100" variant="success" :striped="true" >
                            <div class="progressLabel">{{ row.item.sumPercentDownloaded.toFixed(1)}} % of all torrents data downloaded</div>
                            <b-progress-bar :value="row.item.sumPercentDownloaded">                       
                            </b-progress-bar>
                        </b-progress>
                        <b-badge v-if="row.item.someExtra" variant="warning">has extra torrents</b-badge>    
                    </template>
                    <template v-else>
                        <b-badge v-if="row.item.connected!=true && row.item.active==1" variant="dark">api not reached</b-badge>  
                        <b-badge v-if="row.item.torrentCount==0" variant="info">nothing to do</b-badge>      
                        <b-badge v-if="row.item.active==0" variant="danger">inactive</b-badge>                     
                    </template>
            </template>
            <template slot="id" slot-scope="row">
                <b-btn v-if="row.item.connected && row.item.active==1" pill variant="primary" size="sm" class="btn-ssm" @click="toggleDetail(row)">view details</b-btn>
                <b-btn pill variant="primary" size="sm" class="btn-ssm" @click="toggleEdit(row)">edit</b-btn>
                <b-btn pill variant="danger" size="sm" class="btn-ssm" @click.stop="deleteClient(row)">delete</b-btn>
                <b-btn  v-if="row.item.active==0" pill variant="info" size="sm" class="btn-ssm" @click.stop="activateClient(row)">activate</b-btn>
                <b-btn  v-if="row.item.active==1" pill variant="danger" size="sm" class="btn-ssm" @click.stop="inactivateClient(row)">inactivate</b-btn>              
            </template>
            <template slot="address" slot-scope="row">
                {{row.item.address}}:{{row.item.port}}
            </template>
             <template slot="sumDownload" slot-scope="row">
                            {{getReadableDownloadSpeed(row.item.sumDownload)}}
            </template>
            <template slot="sumUpload" slot-scope="row">
                            {{getReadableDownloadSpeed(row.item.sumUpload)}}
            </template>
            <template slot="row-details" slot-scope="row">
                <div v-show="row.item.edit">
                    <b-card >
                        <h3 slot="header">Edit client</h3>
                        <b-form>
                            <b-container class="bv-example-row">
                                <b-row>
                                    <b-col>
                                        <b-form-group id="clientgroupsgr"
                                            label="Groups "
                                            label-for="clientgroups"
                                            description="Specify group names (delimited by semicolon).">
                                            <b-form-input 
                                                id="clientgroups"
                                                v-model="groupsconcated[row]" type="text"> 
                                            </b-form-input>
                                        </b-form-group>
                                    </b-col>
                                </b-row>
                                <b-row>
                                    <b-col>
                                        <b-button variant="primary" @click="onClientEditSubmit(row)">Submit</b-button>
                                    </b-col>
                                </b-row>
                            </b-container>
                        </b-form>  
                    </b-card> 
                </div>
                <div v-show="row.item.showDetails">
                    <b-card>
                        <b-table striped hover :items="row.item.torrents" :fields="torrentFields" class="torrents" :small="true">
                            <template slot="stats" slot-scope="row">

                                <b-badge v-if="row.item.forDistribution==false" variant="warning">extra</b-badge>    

                                <template v-if="row.item.started && row.item.checking!=true">
                                    <b-badge v-if="row.item.started" variant="success">seeding</b-badge>
                                    <b-badge v-if="row.item.percentProgress!=100" variant="success">downloading</b-badge>
                                    
                                </template>
                                <b-badge v-if="row.item.started!=true" variant="danger">stopped</b-badge>    
                                <b-badge v-if="row.item.paused" variant="secondary">paused</b-badge>       
                                <b-badge v-if="row.item.checking" variant="success">checking</b-badge>       
                            
                            </template>

                            <template slot="size" slot-scope="row">
                                {{getReadableFileSizeString(row.item.size)}}
                            </template>

                            <template slot="downloadSpeed" slot-scope="row">
                                {{getReadableDownloadSpeed(row.item.downloadSpeed)}}
                            </template>

                            <template slot="uploadSpeed" slot-scope="row">
                                {{getReadableDownloadSpeed(row.item.uploadSpeed)}}
                            </template>
                            
                            <template slot ="hash" slot-scope="row">
                            <b-btn pill variant="danger" size="sm" class="btn-ssm" @click.stop="torrentRemove(row)">remove</b-btn>
                            <b-btn v-if="row.item.started && row.item.paused!=true" pill variant="warning" size="sm" class="btn-ssm" @click.stop="torrentPause(row)">pause</b-btn>
                            <b-btn v-if="row.item.paused" pill variant="success" size="sm" class="btn-ssm" @click.stop="torrentResume(row)">resume</b-btn>
                            <b-btn v-if="row.item.started!=true" pill variant="success" size="sm" class="btn-ssm" @click.stop="torrentStart(row)">start</b-btn>
                            
                            
                            </template>
                        </b-table>          
                    </b-card>
                </div>
            </template>
        </b-table>

        </b-card>

        <!-- distribution administration -->
        <b-card class="mt-3">
            <template slot="header">
            <h6 class="mb-0 left">Distribution list</h6>
              <b-btn v-b-toggle="'collapseTorrent'" class="right btn-ssm" variant="success" size="sm"> Add new torrent to distribution</b-btn>
            </template>

          
            <!-- add torrent to distribution form -->
            <b-collapse id="collapseTorrent" v-model="showNewTorrent">
                <b-card>
                    <b-form>
                        <b-container class="bv-example-row">
                            <b-row>
                                <b-col>
                                    <b-form-group id="newTorrentFileGroup"
                                            label="Torrent file"
                                            label-for="newTorrentFile">
                                        <b-form-file    id="newTorrentFile" 
                                                        multiple
                                                        v-model="newTorrentFile" 
                                                        :state="Boolean(newTorrentFile)" 
                                                        accept=".torrent" 
                                                        placeholder="Choose torrent file or more"></b-form-file>
                                    </b-form-group>
                                </b-col>
                            </b-row>
                            <b-row>
                                <b-col>
                                     <b-form-group id="torrentgroupsgr"
                                            label="Groups "
                                            label-for="torrentgroups"
                                            description="Specify group names (delimited by semicolon).">
                                            <b-form-input 
                                                id="torrentgroups"
                                                v-model="newTorrent.groupsconcated" type="text"> 
                                            </b-form-input>
                                        </b-form-group>
                                </b-col>
                            </b-row>
                            <b-row>    
                                 <b-form-checkbox class="m-3" v-model="newTorrent.active">Active</b-form-checkbox><br>
                            </b-row>
                            <b-row>
                                <b-col>
                                    <b-button variant="primary" @click="onNewTorrentSubmit">Submit</b-button>
                                    <b-button variant="danger" @click="onNewTorrentReset">Cancel</b-button>
                                </b-col>
                            </b-row>
                        </b-container>
                    </b-form>               
                </b-card>
            </b-collapse>

            <!-- distribution list -->
            <b-table striped hover :items="distrList" :fields="distrFields" :small="true" stacked="md">
                <template slot="Id" slot-scope="row">
                        <b-badge v-if="row.item.AllInstalled && row.item.SomePaused!=true && row.item.Active"
                              variant="success">all seeding/downloading</b-badge>             
                        <b-badge v-if="row.item.SomePaused" variant="warning">some are paused or stopped</b-badge>
                        <b-badge v-if="row.item.Active!=true" variant="info">not active</b-badge>    
                        <b-badge v-if="row.item.AllInstalled!=true" variant="danger">not installed everywhere</b-badge>    
                </template>
                 <template slot="Groups" slot-scope="row">
                    <template v-for="gr in row.item.Groups">
                        <b-badge variant="light">{{gr}}</b-badge>
                    </template>
                </template>
                <template slot="Active" slot-scope="row">
                    <b-btn pill variant="primary" size="sm" class="btn-ssm" @click="toggleEditTorrent(row)">edit</b-btn>
                    <b-btn v-if="row.item.Active!=true" pill variant="info" size="sm" class="btn-ssm" @click.stop="onDistActivate(row)">activate</b-btn>
                    <b-btn v-if="row.item.Active" pill variant="danger" size="sm" class="btn-ssm" @click.stop="onDistInactivate(row)">inactivate</b-btn>               
                    <b-btn pill variant="danger" size="sm" class="btn-ssm" @click.stop="onDistItemRemove(row)">remove</b-btn>
                </template>
               <template slot="row-details" slot-scope="row">
                <div v-show="row.item.edit">
                    <b-card >
                        <h3 slot="header">Edit torrent</h3>
                        <b-form>
                            <b-container class="bv-example-row">
                                <b-row>
                                    <b-col>
                                        <b-form-group id="torrentgroupsgr"
                                            label="Groups "
                                            label-for="torrentgroups"
                                            description="Specify group names (delimited by semicolon).">
                                            <b-form-input 
                                                id="torrentgroups"
                                                v-model="groupsconcated[row]" type="text"> 
                                            </b-form-input>
                                        </b-form-group>
                                    </b-col>
                                </b-row>
                                <b-row>
                                    <b-col>
                                        <b-button variant="primary" @click="onTorrentEditSubmit(row)">Submit</b-button>
                                    </b-col>
                                </b-row>
                            </b-container>
                        </b-form>  
                    </b-card> 
                </div>
                </template>
            </b-table>
        </b-card>
       
    </div>
</template>

<script>

module.exports = {
    props:['clients'],
    data: function(){
          return {
                distrList:[],
                distrFields:[
                    {   key: "Name",     sortable: true,   label: "Name"},
                    {   key: "Groups",   sortable:   true, label: "Groups"},
                    {   key: "Id",       sortable:false,   label: "Status flags"},
                    {   key: "Active",     sortable: false,label: "Actions"}
                ],
                groupsconcated:[],
                distSortBy:"name",
                distSortDesc:false,
                showNewTorrent:null,
                newTorrent:{
                    groupName:null,
                    name:null,
                    data:null,
                    active:true,
                    groupsconcated:""
                    },
                newTorrentFile:null,
                cientsSortBy:"connected", 
                clientsSortDesc:true,
                clientsfields:[
                    {   key:"address",      sortable: true, label: "IP adress"},
                    {   key:"groups",       sortable: true, label: "Groups"},
                    {   key:"title",        sortable: true, label: "Label"},
                    {   key:"torrentCount", sortable: true, label: "Torrents"},
                    {   key:"sumUpload",    sortable: true, label: "Up"},
                    {   key:"sumDownload",  sortable: true, label: "Down"},
                    {   key:"last_update",  sortable: false,label: "Status"},
                    {   key:"id",           sortable: false,label: "Actions"}
                            ],
                showNewClient:false,
                newClient:  {
                    address:"",
                    title:"",
                    port:"",
                    active:true,
                    groupsconcated:""
                            },
                torrentFields:[
                    {   key:   "name",              sortable:   true, label:    "Name"},
                    {   key:   "stats",             sortable:   false, label:    "Status flags"},
                    {   key:   "size",              sortable:   true, label:    "Size"},
                    {   key:   "percentProgress",   sortable:   true, label:    "%"},
                    {   key:   "uploadSpeed",       sortable:   true, label:    "Up"},
                    {   key:   "downloadSpeed",     sortable:   true, label:    "Down"},
                    {   key:   "sp",                sortable:   true, label:    "P/S in Swarm"},
                    {   key:   "asp",               sortable:   true, label:    "Active P/S"},
                    {   key:   "ratio",             sortable:   true, label:    "Ratio"},
                    {   key:   "queueOrder",        sortable:   true, label:    "Ord."},
                    {   key:   "hash",        sortable:   false, label:    "Actions"},
                    
                            ]
          }
    },
    created:function()
    {
        this.loadDistList();
        setInterval(this.loadDistList,5000);
        
    },
    methods:
    {
        onClientEditSubmit:function(row)
        {
            vm=this;
            row.item.groups=vm.groupsconcated[row].split(";");
            axios.put(apiPath+"admin/clients/"+row.item.ID,JSON.stringify({groups: row.item.groups}))
                    .then(function (response) {
                    if(response.data.status =="ok")
                    { 
                        if(response.data.messages)
                            vm.$emit("showmessages",response.data.messages);
                        row.toggleDetails();
                    }
                    })
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        onTorrentEditSubmit:function(row)
        {
            var vm=this;
            row.item.groups=vm.groupsconcated[row].split(";");
            axios.put(apiPath+"admin/distlist/"+row.item.Id, JSON.stringify(row.item)).then(function (response) {
                    if(response.data.status =="ok")
                    { 
                        if(response.data.messages)
                            vm.$emit("showmessages",response.data.messages);
                        vm.toggleEditTorrent(row);
                    }})
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        toggleEdit:function(row)
        {
            vm=this;console.log(row);
            if(row.item.edit==true)
                {
                    row.item.edit=false;
                    if(row.item._showDetails)
                        row.toggleDetails();
                }
            else
                {
                    row.item.edit=true;
                    row.item.showDetails=false;
                    vm.groupsconcated[row]=row.item.groups.join(";");
                    if(!row.item._showDetails)
                        row.toggleDetails();
                }
        },
         toggleEditTorrent:function(row)
        {
            vm=this;
            if(row.item.edit==true)
                {
                    row.item.edit=false;
                    if(row.item._showDetails)
                        row.toggleDetails();
                }
            else
                {
                    row.item.edit=true;
                    row.item.showDetails=false;
                    vm.groupsconcated[row]=row.item.Groups.join(";");
                    if(!row.item._showDetails)
                        row.toggleDetails();
                }
        },
        toggleDetail:function(row)
        {
            vm=this;
            if(row.item.showDetails)
                {
                    row.item.showDetails=false;
                    if(row.item._showDetails)
                        row.toggleDetails();
                }
            else
                {
                    row.item.showDetails=true;
                    row.item.edit=false;
                    vm.groupsconcated[row]=row.item.groups.join(";");
                    if(!row.item._showDetails)
                        row.toggleDetails();
                }
           
        },
        activateClient:function(row)
        {
            vm=this;
            axios.put(apiPath+"admin/clients/"+row.item.ID,JSON.stringify({active:true}))
                    .then(function (response) {
                    if(response.data.data !==null)
                    { 
                        vm.$emit("clientschanged",true);
                        vm.$emit("showmessages",response.data.messages);
                    }
                    })
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        inactivateClient:function(row)
        {
            vm=this;
            axios.put(apiPath+"admin/clients/"+row.item.ID,JSON.stringify({active:false}))
                    .then(function (response) {
                    if(response.data.data !==null)
                    { 
                        vm.$emit("clientschanged",true);
                        vm.$emit("showmessages",response.data.messages);
                    }
                    })
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        resetPeers:function()
        {
            var data ={reset:true};
            axios.post(apiPath+"peers","peers="+JSON.stringify(data)).then(function (response) {
                    if(response.data.data !==null)
                    {
                        vm.$emit("showmessages",response.data.messages);
                    }})
                    .catch(function (error) {
                        console.log(error);                       
                    })
        },

        onDistActivate:function(row)
        {
            row.item.Active=true;
            axios.put(apiPath+"admin/distlist/"+row.item.Id, JSON.stringify(row.item)).then(function (response) {
                    if(response.data.data !==null)
                    {
                        vm.$emit("showmessages",response.data.messages);
                    }})
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        onDistInactivate:function(row)
        {
            row.item.Active=false;
            axios.put(apiPath+"admin/distlist/"+row.item.Id, JSON.stringify(row.item)).then(function (response) {
                    if(response.data.data !==null)
                    {
                        vm.$emit("showmessages",response.data.messages);
                    }})
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
         torrentRemove:function(row)
        {
            clientID=row.item.id_client;
            vm=this;
            axios.delete(apiPath+"admin/clients/"+clientID+"/torrents/"+row.item.id).then(function (response) {
                    if(response.data.data !==null)
                    {
                        //vm.$emit("clientschanged",true);
                        vm.$emit("showmessages",response.data.messages);
                    }})
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        torrentStart:function(row)
        {
            clientID=row.item.id_client;
            data=row.item;
            data.started=true;
            vm=this;
            axios.put(apiPath+"admin/clients/"+clientID+"/torrents/"+data.id,JSON.stringify(data)).then(function (response) {
                    if(response.data.data !==null)
                    {
                        //vm.$emit("clientschanged",true);
                        vm.$emit("showmessages",response.data.messages);
                    }})
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        torrentResume:function(row)
        {
            clientID=row.item.id_client;
            data=row.item;
            data.paused=false;
            vm=this;
            axios.put(apiPath+"admin/clients/"+clientID+"/torrents/"+data.id,JSON.stringify(data)).then(function (response) {
                    if(response.data.status =="ok")
                    {
                        //vm.$emit("clientschanged",true);
                        vm.$emit("showmessages",response.data.messages);
                    }})
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        torrentPause:function(row)
        {
            clientID=row.item.id_client;
            data=row.item;
            data.paused=true;
            vm=this;
            axios.put(apiPath+"admin/clients/"+clientID+"/torrents/"+data.id,JSON.stringify(data)).then(function (response) {
                    if(response.data.status =="ok")
                    {
                        //vm.$emit("clientschanged",true);
                        vm.$emit("showmessages",response.data.messages);
                    }})
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },

        deleteClient:function(row)
        {
            var vm=this;
            axios.delete(apiPath+"admin/clients/"+row.item.ID)
                    .then(function (response) {
                    if(response.data.status =="ok")
                    { 
                        vm.$emit("clientschanged",true);
                        vm.$emit("showmessages",response.data.messages);
                    }
                    })
                    .catch(function (error) {
                        console.log(error);
                        
                    })
        },
        onNewClientSubmit:function()
        {
            var vm=this;
            this.newClient.groups=this.newClient.groupsconcated.split(";");
            axios.post(apiPath+"admin/clients","newClient="+JSON.stringify(this.newClient))
                    .then(function (response) 
                        {
                            if(response.data.status =="ok")
                            { 
                                vm.$emit("clientschanged",true);
                                vm.$emit("showmessages",response.data.messages);
                                vm.onNewClientReset();
                            }
                        })
                    .catch(function (error) {
                        console.log(error);
                    })
           
        },
        onNewClientReset:function()
        {
            this.showNewClient=false;//console.log(this.showNewClient);
        },
        loadDistList:function()
        {
            var vm = this
            axios.get(apiPath+"watcher/distlist")
                .then(function (response) {
                    if(response.data.status =="ok")
                    { 
                        vm.updateDistList(response.data.data);
                    }
                    })
                    .catch(function (error) {
                        console.log(error);
                        //vm.messages.push('Could not reach the API. ' + error);
                    })
        },
        updateDistList:function(newDistList)
            {
                if(this.distrList.constructor === Array)
                {
                // APLIKACE STAVU ROZKLIKNUTEHO DETAILU
                    this.distrList.forEach(function(value, index) 
                                {
                                    if(value._showDetails)
                                    {
                                            found=newDistList.find(function(element) {
                                                    if(element.Id==value.Id){
                                                        return element;}
                                                    else{
                                                        return null;}
                                                });
                                        if(found !=null)
                                        {
                                           found._showDetails=value._showDetails;
                                           found.edit=value.edit;
                                        }
                                    }
                                }
                    ); 
                    this.distrList=newDistList;
                }
            },
        onDistItemRemove:function(r)
        {
            var distId= r.item.Id;
            var vm=this;
            axios.delete(apiPath+"admin/distlist/"+distId)
                                        .then(function (response) {
                                        if(response.data.data !=null)
                                        { 
                                            vm.loadDistList();
                                        }
                                        })
                                        .catch(function (error) {
                                            console.log(error);
                                            //vm.messages.push('Could not reach the API. ' + error);
                                        })   
         
        },
        onNewTorrentSubmit:function()
        {
            var vm = this;
           
            vm.newTorrentFile.forEach(f => {
                //console.log(f);
                getBase64(f).then(
                             d => {
                                var decoded=encodeURIComponent(d);
                                nT={name:f.name.substring(0,f.name.length-8),groups:vm.newTorrent.groupsconcated.split(";"),data:decoded,active:vm.newTorrent.active};
                                //console.log(nT);
                                    axios.post(apiPath+"admin/distlist","newTorrent="+JSON.stringify(nT))
                                        .then(function (response) {
                                        if(response.data.data !==null)
                                        { 
                                            vm.loadDistList();
                                        }
                                        })
                                        .catch(function (error) {
                                            console.log(error);
                                            //vm.messages.push('Could not reach the API. ' + error);
                                        })   
                             });
                      
            }); 
            this.showNewTorrent=false;
        },
        onNewTorrentReset:function()
        {
            this.newTorrentFile=null;
            this.showNewTorrent=false;
            this.newTorrent={
                    groupName:null,
                    name:null,
                    data:null,
                    active:true
                    }
        }
    }
}

</script>
