//  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/>.

import QtQuick 2.5
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.12
import QtQml.Models 2.1
import "qrc:/js/image.js" as Imagejs
import "qrc:/js/helper.js" as Helperjs
import "qrc:/qml/photoqml"
import "qrc:/qml/genericqml"


StackView{
    id: photoStack
    initialItem:Rectangle {
        id:fotorectangle
        anchors.fill:parent
        color: Material.backgroundColor
        property var newimages:[]
        property int currentimageno: 0
        property bool remoteContact: false


        onNewimagesChanged:{
            if(fotorectangle.newimages.length>0){
                var ownimagelist=[];
                Helperjs.readField("album",root.db,"imageData",root.login.username,function(albums){
                    for (var i=0;i<fotorectangle.newimages.length;i++){
                        if(albums.indexOf(fotorectangle.newimages[i].album)==-1){
                            filesystem.Directory=root.login.imagestore+"/albums";
                            filesystem.makeDir(fotorectangle.newimages[i].album)}
                        ownimagelist.push(root.login.server+"/api/friendica/photo?photo_id="+fotorectangle.newimages[i].id);
                    }
                    //Imagejs.dataRequest(login,fotorectangle.newimages[0],db,xhr,fotorectangle);
                })
                if(login.password!=""){xhr.setLogin(login.username+":"+Qt.atob(login.password));}
                else{xhr.setToken(login.token)}
                xhr.setImagedir(login.imagestore);
                xhr.setFilelist(ownimagelist);
                xhr.setDownloadtype("picturelist");
                xhr.getlist();
                newImagesProgress.visible=true
            }
        }

        onCurrentimagenoChanged:{
            if(fotorectangle.currentimageno==fotorectangle.newimages.length){
                newImagesProgress.visible=false;showFotos(root.login,"");
                fotorectangle.newimages=[];fotorectangle.currentimageno=0
            }else{
                // download next image
                //Imagejs.dataRequest(login,fotorectangle.newimages[currentimageno],db,xhr,fotorectangle)
            }
        }

        Connections{
            target:xhr
            function onDownloadedjson(type,url,filename,i,jsonObject){
                if(type=="picturelist"){
                    fotorectangle.currentimageno=fotorectangle.currentimageno+1
                    Imagejs.storeImagedata(login,db,jsonObject,fotorectangle)
                }
            }
            function onDownloaded(type,url,filename,i){
                if(type=="picture"){fotorectangle.currentimageno=fotorectangle.currentimageno+1}
            }
            function onError(data,url,api,code){
                if(data=="picturelist"){
//                    var requestid=api.substring(api.lastIndexOf("=")+1);
//                    Imagejs.dataRequest(login,requestid,db,xhr,fotorectangle);
                    fotorectangle.currentimageno=fotorectangle.currentimageno+1
                } else if (data=="picture"){
                    Helperjs.deleteData(root.db,"imageData",root.login.username,function(){
                        fotorectangle.currentimageno=fotorectangle.currentimageno+1
                    },"link",url)
                }else{
                    fotorectangle.currentimageno=fotorectangle.currentimageno+1}
            }
            function onSuccess(text,api){
                if (api=="/api/friendica/photoalbums"){
                    let albums=JSON.parse(text);
                    var msg = { 'model': photogroupModel,'albums':albums,'firstalbum':0,'foreignPicture': false};
                    photoWorker.sendMessage(msg);
                }
            }
        }
        //    Connections{
        //        target:filesystem
        //        onError:{print("Error deleting");
        //            }
        //        onSuccess:print("Success deleting");
        //    }

        function showFotos(login,friend){
            if(friend=="backButton"){
                if (photoStack.depth > 1){photoStack.pop()}
                else if(albumgridview.currentItem==null){rootstack.currentIndex=0}
                else if(albumgridview.currentItem.state=='fullscreen'){
                    albumgridview.currentItem.state = 'inGrid'}
                else if (albumgridview.currentItem.state == 'inGrid'){albumgridview.currentItem.state=''}
                else{rootstack.currentIndex=0}
            }
            else{
                try {photogroupModel.clear()}catch (e){print(e)}
                if (friend){
//                    Imagejs.newRequestFriendsAlbumPictures(login,friend,fotorectangle,function(albums,remoteAuthBool){
//                        remoteContact=remoteAuthBool;
//                        var msg = {'model': photogroupModel,'albums':albums,'firstalbum':0,'foreignPicture':true,'friend':friend}
//                        photoWorker.sendMessage(msg);
//                    })
//                    phototabstatusButton.text=friend.screen_name+qsTr("\'s images")

                }
                else {
                    xhr.setAccount(login);
                    xhr.setApi("/api/friendica/photoalbums");
                    xhr.get();
//                    Helperjs.readField("album", db, "imageData",login.username,function(albums){
//                        if (albums[0]) {
//                            var msg = { 'model': photogroupModel,'albums':albums,'firstalbum':0,'foreignPicture': false};
//                            photoWorker.sendMessage(msg);
//                        }
//                    })
                }
            }
        }

        function deletepics(method, type,id){
            if(method=="delete"){Imagejs.deleteImage(db,login,type, id,filesystem,root,function(){//showFotos("")
            })}
        }
        function updatepic(method,type,id){
            if(method=="update"){
                Helperjs.readData(db,"imageData",login.username,function(url){
                    photoStack.push(
                                "qrc:/qml/photoqml/ImageUploadDialog.qml",{"attachImageURLs":[url[0].location+url[0].filename],"imageId":id,"currentAlbum":url[0].album}
                                )
                },"id",id)}
        }

        function uploadUrls(urls){
            photoStack.push("qrc:/qml/photoqml/ImageUploadDialog.qml",{"attachImageURLs":urls})
        }

        BlueButton{
            z:2
            visible: !wideScreen
            fontColor: Material.secondaryTextColor//"grey"
            border.color: "transparent"
            text: "\uf0c9"
            font.pointSize: osSettings.bigFontSize
            onClicked:{
                leftDrawerAndroid.visible?leftDrawerAndroid.close():leftDrawerAndroid.open()}
        }

        LeftDrawerLinux{
            id:leftDrawer
            property var newstabstatus: newstab.newstabstatus
            visible: wideScreen&&rootstackView.depth<2
            width: visible?root.fontFactor*osSettings.systemFontSize*15:0
            height: root.height-bar.height
        }

        LeftDrawerAndroid{
            id: leftDrawerAndroid
        }

        ProgressBar{
            id: newImagesProgress
            width: 15*mm
            height: updatePhotolist.height
            anchors.top: parent.top
            anchors.right:uploadPhoto.left
            anchors.rightMargin:mm
            visible: false
            value: fotorectangle.currentimageno/fotorectangle.newimages.length
        }

        MButton{
            id:  uploadPhoto
            anchors.top: parent.top
            anchors.topMargin: 0.5*mm
            anchors.right:updatePhotolist.left
            anchors.rightMargin:mm
            text:"\uf0ee"
            onClicked: {photoStack.push("qrc:/qml/photoqml/ImageUploadDialog.qml")}
        }

        MButton{
            id:  updatePhotolist
            anchors.top: parent.top
            anchors.topMargin: 0.5*mm
            anchors.right:phototabstatusButton.left
            anchors.rightMargin:mm
            text:"\uf0ed"

            Menu {
                id:photoupdatemenu
                width:8*root.fontFactor*osSettings.bigFontSize
                MenuItem {
                    text: qsTr("All Images")
                    font.pointSize: osSettings.bigFontSize
                    onTriggered: {
                        Imagejs.requestList(root.login,root.db, false, fotostab,function(obj){fotorectangle.newimages=obj})}
                }
                MenuItem {
                    text: qsTr("Only new")
                    font.pointSize: osSettings.bigFontSize
                    onTriggered: {
                        Imagejs.requestList(root.login,root.db, true,fotostab,function(obj){fotorectangle.newimages=obj})}
                }
            }
            onClicked: {photoupdatemenu.popup()}
        }

        MButton{
            id:  phototabstatusButton
            anchors.top: parent.top
            anchors.topMargin: 0.5*mm
            anchors.right: parent.right
            anchors.rightMargin:2*mm
            width: Math.max(8*root.fontFactor*osSettings.bigFontSize,implicitWidth)
            text: fotostab.phototabstatus=="Images"?qsTr("Own Images"):fotostab.phototabstatus
            Menu {
                id:phototabmenu
                width: 20*root.fontFactor*osSettings.bigFontSize
                MenuItem {
                    text: qsTr("Own Images")
                    font.pointSize: osSettings.bigFontSize
                    onTriggered: {
                        fotostab.phototabstatus="Images";
                        // phototabstatusButton.text=qsTr("Own images");
                        showFotos(root.login,"")}
                }
            }
            onClicked: {phototabmenu.popup()}
        }


        DelegateModel{
            id: visualphotoModel
            delegate: PhotogroupComponent{}
            model: photogroupModel
        }

        ListModel{
            id: photogroupModel
        }

        GridView {
            id: albumgridview
            cellWidth: 17*mm
            cellHeight: 17*mm
            x: leftDrawer.width
            y:8*mm
            width: wideScreen&&rootstackView.depth<2?parent.width-leftDrawer.width-mm:parent.width-mm
            height: parent.height-9*mm
            clip: true
            model: visualphotoModel.parts.album
            footer:Rectangle{
                border.color: Material.backgroundDimColor
                border.width: 1
                color: Material.dialogColor
                width:12*mm
                height:6*mm
                Text{
                    color: Material.primaryTextColor
                    font.pointSize: 0.75*osSettings.systemFontSize
                    anchors.centerIn: parent
                    text:qsTr("More")
                }
                MouseArea{anchors.fill:parent
                    onClicked:{
                        var lastalbum_id=photogroupModel.count-1;
                        if(photogroupModel.get(photogroupModel.count-1).foreignPicture==true){
//                            Imagejs.newRequestFriendsAlbumPictures(login,photogroupModel.get(0).friend,fotorectangle,function(albums,remoteAuthBool){
//                                remoteContact=remoteAuthBool;
//                                var msg = {'model': photogroupModel,'albums':albums,'firstalbum':lastalbum_id+1,'foreignPicture':true,'friend':photogroupModel.get(0).friend}
//                                photoWorker.sendMessage(msg)
//                            })
                        }
                        else{Helperjs.readField("album",root.db, "imageData",root.login.username,function(albums){
                            var msg = { 'model': photogroupModel,'albums':albums,'foreignPicture': false,'firstalbum':lastalbum_id+1};
                            photoWorker.sendMessage(msg)})}
                    }}}
        }

        Rectangle { id: photoBackground; color: 'black'; width: parent.width; height: parent.height; opacity: 0; visible: opacity != 0.0 }

        ListView { width: parent.width; height:parent.height; model: visualphotoModel.parts.browser; interactive: false }

        MButton {
            id: backButton
            text: "\uf057"
            x: parent.width - backButton.width - root.fontFactor*osSettings.bigFontSize
            y: -backButton.height - root.fontFactor*osSettings.bigFontSize
            z:2
            onClicked: {photoBackground.opacity=0}
        }

        ListView {anchors.fill: parent; model: visualphotoModel.parts.fullscreen; interactive: false }
        WorkerScript{id: photoWorker;source: "qrc:/js/photoworker.js"}

        Component.onCompleted: {
            root.fotoSignal.connect(showFotos);
            root.uploadSignal.connect(uploadUrls);
            root.changeimage.connect(deletepics);
            root.changeimage.connect(updatepic);
            if (fotostab.phototabstatus=="Images"){showFotos(root.login,"")}
        }
    }
}