//  This file is part of Friendiqa
//  https://git.friendi.ca/lubuwest/Friendiqa
//  Copyright (C) 2020 Marco R. <thomasschmidt45@gmx.net>
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  In addition, as a special exception, the copyright holders give
//  permission to link the code of portions of this program with the
//  OpenSSL library under certain conditions as described in each
//  individual source file, and distribute linked combinations including
//  the two.
//
//  You must obey the GNU General Public License in all respects for all
//  of the code used other than OpenSSL. If you modify file(s) with this
//  exception, you may extend this exception to your version of the
//  file(s), but you are not obligated to do so. If you do not wish to do
//  so, delete this exception statement from your version. If you delete
//  this exception statement from all source files in the program, then
//  also delete it here.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <http://www.gnu.org/licenses/>.

.pragma library
.import QtQuick.LocalStorage 2.0 as Sql
.import "qrc:/js/helper.js" as Helperjs

function requestList(login,database,onlynew,rootwindow,callback) {
    //get list of own images and call download function
    Helperjs.friendicaRequest(login,"/api/friendica/photos/list", rootwindow,function (helperobject){
   //print("return"+helperobject);
   var obj=JSON.parse(helperobject);
   if (onlynew){Helperjs.readField("id",database,"imageData",login.username,function(AllStoredImages){
        if (AllStoredImages.length>0){
            for(var i=0;i< AllStoredImages.length;i++){
                var position=Helperjs.inArray(obj,"id",AllStoredImages[i]);
                if (position>-1){obj.splice(position,1)}
             }
        }
      callback(obj)
    })}
   else{callback(obj)}
})}

function dataRequest(login,photoID,database,xhr,rootwindow) {
    // check if image exist and call download function
    Helperjs.friendicaRequest(login,"/api/friendica/photo?photo_id="+photoID, rootwindow, function (image){
        try{ if(image==""){currentimageno=currentimageno+1}else{
            var obj = JSON.parse(image);
            var helpfilename=obj.filename.substring(0,obj.filename.lastIndexOf("."));
            var filesuffix="";
            if (obj.type=="image/jpeg"){filesuffix=".jpg"}
            else if (obj.type=="image/png"){filesuffix=".png"}
            else {filesuffix=""}
            if (helpfilename==""){// check if file has any filename
                obj.filename=obj["id"]+filesuffix;
            }
            else{obj.filename=helpfilename+filesuffix}
            var link="";
            if(obj["link"][0]){link=obj["link"][0]} else{link=obj["link"]["4"]}
            xhr.setUrl(Qt.resolvedUrl(link));
            xhr.setLogin(login.username+":"+Qt.atob(login.password));
            xhr.setFilename(login.imagestore+'albums/'+obj.album+"/"+obj["filename"]);
            xhr.setDownloadtype("picture");
            xhr.download();
            var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
            db.transaction( function(tx) {
               var result = tx.executeSql('SELECT * from imageData where id = "'+obj["id"]+'"');
               if(result.rows.length === 1) {// use update
               result = tx.executeSql('UPDATE imageData SET username ="' +login.username+ '",id="'+obj.id+'", created="'+obj.created+'", edited="'+obj.edited+'", profile="'+obj.profile+'", link="'+obj["link"]["4"]+'", filename="'+obj.filename+'",title="'+obj.title+'", desc="'+obj.desc+'",   type="'+obj.type+'", width="'+obj.width+'", height="'+obj.height+'", album="'+obj.album+'", location="file://'+login.imagestore+'albums/'+obj.album+'/" where id="'+obj["id"]+'"');
               } else {// use insert print('... does not exists, create it')
               result = tx.executeSql('INSERT INTO imageData VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [login.username,obj.id,obj.created,obj.edited, obj.title, obj.desc, obj.album, obj.filename, obj.type, obj.height, obj.width,obj. profile,obj["link"]["4"],'file://'+login.imagestore+'albums/'+obj.album+"/"]);
               }
           })}}
           catch (e){print("Data retrieval failure! "+ e+obj);}
})}

function storeImagedata(login,database,imagedata,rootwindow) {
    // check if image exist and call download function
            var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
            db.transaction( function(tx) {
               var result = tx.executeSql('SELECT * from imageData where id = "'+imagedata["id"]+'"');
               if(result.rows.length === 1) {// use update
               result = tx.executeSql('UPDATE imageData SET username ="' +login.username+ '",id="'+imagedata.id+'", created="'+imagedata.created+'", edited="'+imagedata.edited+'", profile="'+imagedata.profile+'", link="'+imagedata.link[0]+'", filename="'+imagedata.filename+'",title="'+imagedata.title+'", desc="'+imagedata.desc+'",   type="'+imagedata.type+'", width="'+imagedata.width+'", height="'+imagedata.height+'", album="'+imagedata.album+'", location="file://'+login.imagestore+'albums/'+imagedata.album+'/" where id="'+imagedata["id"]+'"');
               } else {// use insert print('... does not exists, create it')
               result = tx.executeSql('INSERT INTO imageData VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [login.username,imagedata.id,imagedata.created,imagedata.edited, imagedata.title, imagedata.desc, imagedata.album, imagedata.filename, imagedata.type, imagedata.height, imagedata.width,imagedata. profile,imagedata.link[0],'file://'+login.imagestore+'albums/'+imagedata.album+"/"]);
               }
})}

function deleteImage(database,login,type,location,filesystem,rootwindow,callback) { // delete image locally and on server
    var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
    var rsfilename=location.substring(location.lastIndexOf("/")+1,location.length);
    var rslocation=location.substring(0,location.lastIndexOf("/")+1);
    //print(type+" Name "+ rsfilename+" Location: "+rslocation)
    db.transaction( function(tx) {
        if (type=='image'){
            var rs= tx.executeSql('SELECT * FROM imageData WHERE filename="'+rsfilename+'" AND location="'+rslocation+'"')
            var imageId=rs.rows.item(0).id;
            Helperjs.friendicaPostRequest(login,"/api/friendica/photo/delete?photo_id="+imageId,"","DELETE",rootwindow, function (obj){
                //var deletereturn = JSON.parse(obj); print(obj);
                //if (deletereturn.result=="deleted"){
                        db.transaction( function(tx) {
                            var deleters=tx.executeSql('DELETE  FROM imageData WHERE location="'+rslocation+'" AND filename="'+rsfilename+'"'); });
                            filesystem.Directory=rslocation.substring(7,rslocation.length-1);
                            filesystem.rmFile(rsfilename)
           //}
            })
        }
        else{
            Helperjs.friendicaPostRequest(login,"/api/friendica/photoalbum/delete?album="+rsfilename,"","DELETE",rootwindow, function (obj){
                //var deletereturn = JSON.parse(obj);
                //if (deletereturn.result=="deleted"){
                    db.transaction( function(tx) {
                        var rs= tx.executeSql('SELECT DISTINCT location FROM imageData WHERE album="'+rsfilename+'" AND username="'+login.username+'"');
                        var locationstring=rs.rows.item(0).location;
                        filesystem.Directory=locationstring.substring(7,locationstring.length-1);
                        filesystem.rmDir();
                        var deleters=tx.executeSql('DELETE  FROM imageData WHERE album="'+location+'"');
                    })
               //}
           })
        }
        callback(location)
    })
}

function updateImage(database,login,type,filesystem,imageId,rootwindow,callback) { // delete image locally and on server
    var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
    Helperjs.readData(database,"imageData",login.username,function(obj){
        db.transaction( function(tx) {
        if (type=='image'){
            var deleters=tx.executeSql('DELETE  FROM imageData WHERE location="'+obj[0].location+'" AND filename="'+obj[0].filename+'"');
             filesystem.Directory=obj[0].location
             filesystem.rmFile(obj[0].filename)
           }
            })
        },"id",imageId);
    callback()
}


function deleteContacts(database,user,callback) { // does nothing useful at the moment
    var db=Sql.LocalStorage.openDatabaseSync(database[0],database[1],database[2],database[3]);
    //print(' delete Image Data() for ' + field +"="+selection)
    db.transaction( function(tx) {
        result1= tx.executeSql('SELECT * FROM contacts a LEFT OUTER JOIN news b ON  a.url==b.uid');
        result2= tx.executeSql('SELECT * FROM contacts a LEFT OUTER JOIN news b ON  a.url==b.uid');
    callback(result)})
}

//function requestFriendsAlbumPictures(login,friend,rootwindow,callback){
//// screenscraping of albums page of contact without user and password
//    Helperjs.friendicaWebRequest(friend.url.replace("profile","photos"),rootwindow,function(photohtml){
//    //print(photohtml);
//    var photoarray=[];
//    var arr = photohtml.split("sidebar-photos-albums-li");
//    for (var i=2;i<arr.length;i++){
//        var albumlink = arr[i].substring(arr[i].indexOf('http'),arr[i].indexOf('class')-2);
//        var albumname=arr[i].substring(arr[i].indexOf('/span')+6,arr[i].indexOf('</a>')-1);
//        var album={'link':albumlink,'name':albumname}
//      photoarray.push(album);
//    }
//    callback(photoarray)
// })
//}

function newRequestFriendsAlbumPictures(login,friend,rootwindow,callback){//print("newRequestFriendsAlbumPictures");
// screenscraping of albums page of contact with remoteAuth
    //commented out for broken remoteauth
    Helperjs.friendicaRemoteAuthRequest(login,friend.url.replace("profile","photos"),friend.url,rootwindow,function(photohtml){
    //Helperjs.friendicaWebRequest(friend.url.replace("profile","photos"),rootwindow,function(photohtml){
        try {var obj=JSON.parse(photohtml);//print ("Photohtml: "+photohtml)
            if (obj.hasOwnProperty('status')){
                Helperjs.friendicaWebRequest(friend.url.replace("profile","photos"),rootwindow,function(photohtml){
                    getAlbumFromHtml(photohtml,false,rootwindow,callback)})
            }}
        catch (e){
            //getAlbumFromHtml(photohtml,true,rootwindow,callback)
            getAlbumFromHtml(photohtml,false,rootwindow,callback)
        }
    })
}

function getAlbumFromHtml(photohtml,remoteAuthBool,rootwindow,callback){
    //print(photohtml);
    var photoarray=[];
    var arr = photohtml.split("sidebar-photos-albums-li");
    for (var i=2;i<arr.length;i++){
        var albumlink = arr[i].substring(arr[i].indexOf('http'),arr[i].indexOf('class')-2);
        var albumname=arr[i].substring(arr[i].indexOf('/span')+6,arr[i].indexOf('</a>')-1);
        var album={'link':albumlink,'name':albumname}//print(albumlink+" "+albumname);
      photoarray.push(album);
    }
    callback(photoarray,remoteAuthBool)
}


function newRequestFriendsPictures(login,link,friend,remoteAuthBool,remoteauth,rootwindow,callback){
// screenscraping of pictures page for given album
    if (remoteAuthBool){
        remoteauth.setUrl(login.server);
        remoteauth.setLogin(login.username+":"+Qt.atob(login.password));
        remoteauth.setContacturl(friend.url);
        Helperjs.friendicaRemoteAuthRequest(login,link,friend.url,rootwindow,function(photohtml){
            getPictureFromHtml(photohtml,remoteAuthBool,function(photoarray){
                callback(photoarray)
            })
        })}
    else{
        Helperjs.friendicaWebRequest(link,rootwindow,function(photohtml){
            getPictureFromHtml(photohtml,remoteAuthBool,function(photoarray){
                callback(photoarray)
            })
        })
    }
}

function getPictureFromHtml(photohtml,remoteAuthBool,callback){
    var photoarray=[];
     var basehtml=photohtml.substring(photohtml.indexOf('<base')+12,photohtml.indexOf('/>',photohtml.indexOf('<base'))-2);

// old theme
   if (photohtml.indexOf("photo-album-image-wrapper-end")>-1){ //theme 1
   var arr = photohtml.split("photo-album-image-wrapper-end");}

// other themes
   if (photohtml.indexOf("photo-album-wrapper")>-1){ //theme 2
        var photoarea=photohtml.substring(photohtml.indexOf("photo-album-wrapper"),photohtml.indexOf("photo-album-end"))
       var arr = photoarea.split("</a>");}
   //print("Url: "+login.server+ "Contacturl: "+friend.url)
//   remoteauth.setUrl(login.server);
//   remoteauth.setLogin(login.username+":"+Qt.atob(login.password));
//   remoteauth.setContacturl(friend.url);
    for (var i=0;i<arr.length-1;i++){
        var photoname=arr[i].substring(arr[i].lastIndexOf('alt')+5,arr[i].lastIndexOf('title')-2);
        var thumblink=arr[i].substring(arr[i].lastIndexOf('<img')+10,arr[i].lastIndexOf('alt')-2);
        var imagetype=thumblink.substring(thumblink.lastIndexOf("."));
        var photolink=thumblink.substring(0,thumblink.length-imagetype.length-2)+"-0"+imagetype
        if(thumblink.substring(0,4)!=="http"){thumblink=basehtml+thumblink}
        if(photolink.substring(0,4)!=="http"){photolink=basehtml+photolink}
        if(remoteAuthBool){
            thumblink="image://remoteauthimage/"+thumblink;
            photolink="image://remoteauthimage/"+photolink;
        }
        //Helperjs.friendicaRemoteAuthRequest(login,thumblink,friend.url,rootwindow,function(thumbimage){thumbbase64=QT.btoa(thumbimage)});
        //thumblink="image://remoteauthimage/"+login.username+":"+Qt.atob(login.password)+"@"+login.server+"/api/friendica/remoteauth?c_url="+friend.url+"&url="+thumblink;
        var photo={'link':photolink,'name':photoname,'thumb':thumblink}
      photoarray.push(photo);
    }
    callback(photoarray)
}


function requestFriendsPictures(link,rootwindow,callback){
// screenscraping of pictures page for given album
    Helperjs.friendicaWebRequest(link,rootwindow,function(photohtml){
    var photoarray=[];
     var basehtml=photohtml.substring(photohtml.indexOf('<base')+12,photohtml.indexOf('/>',photohtml.indexOf('<base'))-2);

// old theme
   if (photohtml.indexOf("photo-album-image-wrapper-end")>-1){ //theme 1
   var arr = photohtml.split("photo-album-image-wrapper-end");}

// other themes
   if (photohtml.indexOf("photo-album-wrapper")>-1){ //theme 2
        var photoarea=photohtml.substring(photohtml.indexOf("photo-album-wrapper"),photohtml.indexOf("photo-album-end"))
       var arr = photoarea.split("</a>");}

    for (var i=0;i<arr.length-1;i++){
        var photoname=arr[i].substring(arr[i].lastIndexOf('alt')+5,arr[i].lastIndexOf('title')-2);
        var thumblink=arr[i].substring(arr[i].lastIndexOf('<img')+10,arr[i].lastIndexOf('alt')-2);
        var imagetype=thumblink.substring(thumblink.lastIndexOf("."));
        var photolink=thumblink.substring(0,thumblink.length-imagetype.length-2)+"-0"+imagetype
        if(thumblink.substring(0,4)!=="http"){thumblink=basehtml+thumblink}
        if(photolink.substring(0,4)!=="http"){photolink=basehtml+photolink}
        var photo={'link':photolink,'name':photoname,'thumb':thumblink}
      photoarray.push(photo);
    }
    callback(photoarray)
    })
}