//  This file is part of Friendiqa
//  https://git.friendi.ca/lubuwest/Friendiqa
//  Copyright (C) 2017 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.7
import QtQuick.Dialogs 1.2
import QtQuick.Controls 1.2

import "qrc:/js/service.js" as Service
import "qrc:/js/layout.js" as Layoutjs
import "qrc:/js/helper.js" as Helperjs
import "qrc:/qml/configqml"
import "qrc:/qml/genericqml"

StackView{
   id: configStack
   anchors.fill:parent
   initialItem: Flickable{
    width:root.width-5*mm
    height:root.height-12*mm
    contentHeight: configBackground.height
    boundsBehavior: Flickable.StopAtBounds
   
    Rectangle{
        id:configBackground
        color: "white"
        width:parent.width
        height:Math.max(90*mm,root.height-12*mm)
        property var users:[]
        property bool registeredUser: true
        property var userdata: ({})

        function setServericon(server){
           try {Helperjs.friendicaWebRequest(server+"/api/statusnet/config",configBackground, function (obj){
               var serverdata = JSON.parse(obj);
               servericon.visible=true;
               servericon.source=serverdata.site.logo})} catch(e){print(e)}
        }

        BlueButton{
            id:userButton
            text:qsTr("User")
            y:mm
            width: root.width/2
            onClicked:{
                var useritems="";
                for (var i=0;i<configBackground.users.length;i++){

                    useritems=useritems+"MenuItem{text:'"+configBackground.users[i].username+
                        "'; onTriggered: {Service.readConfig(db,function(obj){
                        configBackground.registeredUser=true;
                        userButton.text=obj.username;
                        servername.text=obj.server;
                        configBackground.setServericon(obj.server);
                        username.text= obj.username;
                        password.text=Qt.atob(obj.password);
                        imagestore.text=obj.imagestore;
                        maxNews.value=obj.maxnews;
                        newsTypeField.text=obj.newsViewType;
                        if( obj.isActive==0){userButton.fontColor='black'} else {userButton.fontColor='grey'}
                        },'username','"+configBackground.users[i].username+"')}}"
                    }
                var menuString="import QtQuick.Controls 1.4;import 'qrc:/js/service.js' as Service; Menu {"+useritems+"}";
                var userlistObject=Qt.createQmlObject(menuString,configBackground,"usermenuOutput")
                userlistObject.popup()  }
            }

    Text {
        text: qsTr("Server")
        font.pixelSize:3*mm
        x: 4*mm; y: 10*mm
    }
    Text {
        text: qsTr("Nickname")
        font.pixelSize:3*mm
        x: 4*mm; y: 20*mm
    }

    Text {
        text: qsTr("Password")
        font.pixelSize:3*mm
        x: 4*mm; y: 30*mm
      }
    Text {
        text: qsTr("Image dir.")
        font.pixelSize:3*mm
        x: 4*mm; y: 40*mm
     }

    Text {
        text: qsTr("Max. News")
        font.pixelSize:3*mm
        x: 4*mm; y: 50*mm
     }
    Text {
        text: qsTr("News as")
        font.pixelSize:3*mm
        x: 4*mm; y: 60*mm
    }
    Text {
        text: qsTr("Sync Interval (0=None)")
        font.pixelSize:3*mm
        //visible: false
        x: 4*mm; y: 70*mm; //width:35*mm;wrapMode: Text.Wrap
    }
      
//    Text {
//          text: qsTr("Show Website")
//          x: 4*mm; y:80*mm; width: 20*mm
//    }

    Image{
        id:servericon
        x:4*mm;y:13.5*mm
        width:5*mm; height: 5*mm
        visible: false
        source:""
        MouseArea{
            anchors.fill:parent
            onClicked:{
                Service.showServerConfig(servername.text, configBackground, function(configString){
                var serverconfigObject=Qt.createQmlObject(configString,configBackground,"serverconfigOutput");})
            }
        }
    }

    BlueButton{
        id:serverSearchButton
        text:"\uf002"
        x:4*mm
        y:13.5*mm
        width: 5*mm; height:5*mm
        visible: servericon.visible?false:true
        onClicked:{Qt.openUrlExternally(Qt.resolvedUrl("https://dir.friendica.social/servers"))}
    }

    Rectangle{color: "light grey";  x: 10*mm; y: 13.5*mm; width: root.width-12*mm; height: 5*mm;}
    Flickable {
        id: servernameFlickable
        x: 10*mm; y: 13.5*mm; width: root.width-12*mm; height: 5*mm;
        contentWidth: servername.paintedWidth
        contentHeight: servername.paintedHeight
        clip: true
        TextEdit {
            id: servername
            width: servernameFlickable.width
            height: servernameFlickable.height
            focus: true
            font.pixelSize:3*mm
            text:"https://..."
            onEditingFinished:{
                 if((servername.text).substring(0,14) =="https://...http"){
                     serverstring.text= (serverstring.text).substring(11)
                 }
               configBackground.setServericon(servername.text)
             }
            onCursorRectangleChanged: Layoutjs.ensureVisibility(cursorRectangle,servernameFlickable)
        }
    }

    Rectangle{
        color: "light grey"
        x: 4*mm; y: 23.5*mm; width: root.width-14*mm; height: 5*mm;
        TextInput {
            id: username
            anchors.fill: parent
            font.pixelSize:3*mm
            selectByMouse: true
            onEditingFinished:{
                if (username.text.indexOf('@')>-1){
                    Helperjs.showMessage(qsTr("Error"),qsTr("Nicknames containing @ symbol currently not supported"),configBackground)
                }
             //    Helperjs.friendicaWebRequest(servername.text+'/api/users/show?screen_name='+username.text,configBackground,function(obj){
             //        var screennametest=JSON.parse(obj);
            //         if (screennametest.hasOwnProperty('status')){
            //              Helperjs.showMessage(qsTr("Error"),qsTr("Nickname not registered at given server!"),configBackground);
           //              configBackground.registeredUser=false;
           //          }else{configBackground.registeredUser=true}
           //      });
           //  }
            }
         }
    }
    BlueButton {
        x: root.width-9*mm; y: 23.5*mm; width:7*mm
        text: "\uf234"
        onClicked: {
            configStack.push({item:"qrc:/qml/configqml/RegisterPage.qml",properties:{url:servername.text+"/register?nickname="+username.getText(0,username.length)}})
        }
    }

    Rectangle{
        color: "light grey"
         x: 4*mm; y: 33.5*mm; width: root.width-6*mm; height: 5*mm;
         TextInput {
             id: password
             anchors.fill: parent
             font.pixelSize:3*mm
             selectByMouse: true
             echoMode: TextInput.PasswordEchoOnEdit
        }
    }

    Rectangle{color: "light grey"; x: 4*mm; y: 43.5*mm; width: root.width-14*mm; height: 5*mm;}
    Flickable {
         id: imagestoreFlickable
         x: 4*mm; y: 43.5*mm; width: root.width-14*mm; height: 5*mm;
         clip: true
         TextInput {
             id: imagestore
             width: imagestoreFlickable.width
             height: imagestoreFlickable.height
             font.pixelSize:3*mm
             wrapMode: TextEdit.NoWrap
             onCursorRectangleChanged: Layoutjs.ensureVisibility(cursorRectangle,imagestoreFlickable)
         }
     }

    FileDialog {
        id: imagestoreDialog
        title: "Please choose a directory"
        folder: shortcuts.pictures
        selectFolder: true
        onAccepted: {
            var imagestoreString=imagestoreDialog.folder.toString();
            imagestoreString=imagestoreString.replace(/^(file:\/{2})/,"")+"/"
            imagestore.text=imagestoreString
        }
    }

     BlueButton {
            x: root.width-9*mm; y: 43.5*mm; width: 7*mm; height: 5*mm;
            text: "..."
            onClicked:
         {imagestoreDialog.open()}
     }


    Slider{ id: maxNews
        x:19*mm; y: 53.5*mm;width: root.width/2;height:5*mm
        minimumValue: 0;maximumValue:2000; stepSize: 100
    }


    Rectangle{color: "light grey"; x: 4*mm; y: 53.5*mm; width: 9*mm; height: 5*mm;
        TextEdit{id:maxNewsText;
            anchors.fill: parent
            font.pixelSize:3*mm
            verticalAlignment:TextEdit.AlignRight
            text:maxNews.value
            focus: true
            selectByMouse: true
        }
    }

    Rectangle{
         x: 4*mm; y: 63.5*mm; width: newsTypeField.contentWidth+2*mm; height: 5*mm;
         color:"light grey"
         Text{
             id: newsTypeField
             anchors.fill: parent
             font.pixelSize:3*mm
             text:"Conversations"
        }
        MouseArea{
            anchors.fill:parent
            onClicked:newstypemenu.popup()
        }
    }
    Slider{ id: messageIntervalSlider
        x:22*mm; y: 73.5*mm;width: root.width/2;height:5*mm
        minimumValue: 0;maximumValue:120; stepSize: 15
    }
    Rectangle{
         x: 4*mm; y: 73.5*mm; width: 9*mm; height: 5*mm;
         TextEdit{
             id: messageIntervalField
             anchors.fill: parent
             font.pixelSize:3*mm
             verticalAlignment:TextEdit.AlignRight
             text:messageIntervalSlider.value
             focus: true
             selectByMouse: true
        }
    }
    Text{x: 14*mm; y: 73.5*mm; width: 5*mm; height: 5*mm;
        font.pixelSize:3*mm
        text:qsTr("Min.")
    }

//    CheckBox{
//        id:showwebsiteCheckbox
//        x:35*mm;y:80*mm
//        onClicked:{
//            if (checked==true){
//                Service.updateglobaloptions(root.db,"showWebsiteForLinks","true")
//                root.globaloptions.showWebsiteForLinks="true"
//            }
//            else {
//                Service.updateglobaloptions(root.db,"showWebsiteForLinks","false")
//                root.globaloptions.showWebsiteForLinks="false"
//            }
//        }
//    }

    BlueButton {
    x: 4*mm; y: 83.5*mm
    text: qsTr("Confirm")
    onClicked:{
         var userconfig={server: servername.text, username: username.text, password:Qt.btoa(password.text), imagestore:imagestore.text,maxnews:maxNewsText.text,interval:  messageIntervalField.text, newsViewType:newsTypeField.text};
         var errormessage="";
         if (servername.text==""){errormessage=qsTr("No server given! ")}
         else if (username.text==""){errormessage+=qsTr("No nickname given! ")}
         else if ((configBackground.registeredUser==false)){errormessage+=qsTr("Nickname not registered at given server! ")}
         else if (password.text=="") {errormessage+=qsTr("No password given! ")}
         else if (imagestore.text=="") {errormessage+=qsTr("No image directory given!")}
         else if (maxNewsText.text=="") {errormessage+=qsTr("No maximum news number given!")}
         else {errormessage=""}
         if (errormessage=="") {
             Helperjs.friendicaRequest(userconfig,"/api/account/verify_credentials?skip_status=true",root,function(obj){
                 var credentials=JSON.parse(obj);
                 if (credentials.hasOwnProperty('status')){
                     Helperjs.showMessage(qsTr("Error"),qsTr("Wrong password!"),root)
                 }
                 else{
                     filesystem.Directory=userconfig.imagestore;
                     filesystem.makeDir("contacts");
                     filesystem.makeDir("albums");
                     Service.storeConfig(db,userconfig);
                     Service.readConfig(db,function(userconfig){
                         Helperjs.readData(db,"config","",function(storedUsers){
                            storedUsers.sort(function(obj1, obj2) {
                                return obj1.isActive - obj2.isActive;
                            });
                         configBackground.users=storedUsers});
                         userButton.color="black"
                         //reset values
                         root.login=userconfig;
                         root.news=[];
                     },"isActive",0);
                     Service.requestProfile(userconfig,db,root,function(nc){root.newContacts=nc});
                     if(osSettings.osType=="Android" && userconfig.timerInterval !=0){
                             alarm.setAlarm(userconfig.timerInterval);
                         }
                     Helperjs.showMessage(qsTr("Success"),qsTr("Name")+": "+credentials.name+"\nScreen Name: "+credentials.screen_name,root)
                 }
             });

        }
         else {Helperjs.showMessage(qsTr("Error"), errormessage,root)}
    }}



    BlueButton {
    x: root.width/2+2*mm; y: mm; width: 5*mm; height: 5*mm;
    text: "-"
    onClicked:{
        var userconfig={server: servername.text, username: username.text, password: Qt.btoa(password.text)};
        Service.deleteConfig(db,userconfig,function(){
           filesystem.Directory=imagestore.text+"contacts";
           filesystem.rmDir();
           filesystem.Directory=imagestore.text+"albums";
           filesystem.rmDir();
           configBackground.registeredUser=true;
           servername.text="https://...";
           servericon.visible=false;
           servericon.source="";
           username.text="";
           password.text="";
           imagestore.text="";
           maxNews.value=0;
           newsTypeField.text="Conversations";
           messageIntervalSlider.value=30;
           userButton.text=qsTr("User");
           Helperjs.readData(db,"config","",function(storedUsers){
             storedUsers.sort(function(obj1, obj2) {
                 return obj1.isActive - obj2.isActive;
             })
             configBackground.users=storedUsers;})
       })
    }}

    BlueButton {
    x: root.width/2+8*mm; y: mm; width: 5*mm; height: 5*mm;
    text: "+"
    onClicked:{
        configBackground.registeredUser=true;
        servername.text="https://..."
        servericon.visible=false;
        servericon.source="";
        username.text=""
        password.text=""
        imagestore.text=""
        maxNews.value=0
        newsTypeField.text="Conversations"
        messageIntervalSlider.value=30
        userButton.text=qsTr("User")
       }
     }

    BlueButton {
        x: root.width/2+14*mm; y: mm; width: 5*mm; height: 5*mm;
        text: "?"
        onClicked:{
                    configStack.push({item:"qrc:/qml/configqml/InfoBox.qml"});
           }
         }

    Menu {
        id:newstypemenu
        MenuItem {
            text: qsTr("Timeline")
            onTriggered: {newsTypeField.text="Timeline"}
            }
        MenuItem {
            text: qsTr("Conversations")
            onTriggered: {newsTypeField.text="Conversations"}
            }
    }

   Component.onCompleted: {
      try{Helperjs.readData(db,"config","",function(storedUsers){
          storedUsers.sort(function(obj1, obj2) {
              return obj1.isActive - obj2.isActive;
          })
          configBackground.users=storedUsers;
          Service.readConfig(db,function(obj){
            userButton.text=obj.username;
            servername.text=obj.server;
            configBackground.setServericon(obj.server);
            username.text= obj.username;
            password.text=Qt.atob(obj.password);
            imagestore.text=obj.imagestore;
            maxNews.value=obj.maxnews;
            newsTypeField.text=obj.newsViewType;
            messageIntervalSlider.value=obj.timerInterval;
            if( obj.isActive==0){userButton.fontColor='black'} else {userButton.fontColor='grey'}},"isActive",0
            )
          })
//            Service.readGlobaloptions(db,function(go){
//                if (root.globaloptions.showWebsiteForLinks!="false"){showwebsiteCheckbox.checked=true}
//            })
  
          }
      catch (e){print(e)
          Helperjs.friendicaWebRequest("https://dir.friendica.social/servers/surprise",configBackground,function(html){
              var bpos=html.indexOf("baseurl");
              var baseurl=html.substring(html.indexOf("http",bpos),html.indexOf('"',html.indexOf("http",bpos)));
              servername.text=baseurl
          })}
    }
}
}
}