//  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.0
import QtQuick.Controls 2.12
import QtQuick.Controls.Material 2.12
import "qrc:/qml/genericqml"
import "qrc:/js/service.js" as Service

Rectangle {
//    width:parent.width-2*mm
//    height:parent.height-14*mm
    anchors.fill:parent
    color: Material.backgroundColor//color:"white"
    property var profile:({})
    property var attachImageURLs:[]
    property var createdAtDate: new Date(profile.friendica_owner.created_at)

    function updateProfileImage(){
        xhr.url= login.server + "/api/account/update_profile_image.json";
        xhr.setLogin(login.username+":"+Qt.atob(login.password));
        xhr.clearParams();
        xhr.setImageFileParam("image", photoImage.source );
        xhr.post();
     }

    function buildProfiletext(pobject,callback){
        var profileobject={};
        var profiletext="";
        for (var key in pobject){
            if(pobject[key]!=""&&pobject[key]!=null&&key!="users"&&key!="profile_id"){
                var keytext="";
                switch(key){
                    case "profile_name":keytext=qsTr("profile name");break;
                    case "is_default":keytext=qsTr("is default");break;
                    case "hide_friends":keytext=qsTr("hide friends");break;
                    case "profile_photo":keytext=qsTr("profile photo");break;
                    case "profile_thumb":keytext=qsTr("profile thumb");break;
                    case "publish":keytext=qsTr("publish");break;
                    case "net_publish":keytext=qsTr("publish in network");break;
                    case "description":keytext=qsTr("description");break;
                    case "date_of_birth":keytext=qsTr("date of birth");break;
                    case "address":keytext=qsTr("address");break;
                    case "city":keytext=qsTr("city");break;
                    case "region":keytext=qsTr("region");break;
                    case "postal_code":keytext=qsTr("postal code");break;
                    case "country":keytext=qsTr("country");break;
                    case "hometown":keytext=qsTr("hometown");break;
                    case "gender":keytext=qsTr("gender");break;
                    case "marital":keytext=qsTr("marital status");break;
                    case "marital_with":keytext=qsTr("married with");break;
                    case "marital_since":keytext=qsTr("married since");break;
                    case "sexual":keytext=qsTr("sexual");break;
                    case "politic":keytext=qsTr("politics");break;
                    case "religion":keytext=qsTr("religion");break;
                    case "public_keywords":keytext=qsTr("public keywords");break;
                    case "private_keywords":keytext=qsTr("private keywords");break;
                    case "likes":keytext=qsTr("likes");break;
                    case "dislikes":keytext=qsTr("dislikes");break;
                    case "about":keytext=qsTr("about");break;
                    case "music":keytext=qsTr("music");break;
                    case "book":keytext=qsTr("book");break;
                    case "tv":keytext=qsTr("tv");break;
                    case "film":keytext=qsTr("film");break;
                    case "interest":keytext=qsTr("interest");break;
                    case "romance":keytext=qsTr("romance");break;
                    case "work":keytext=qsTr("work");break;
                    case "education":keytext=qsTr("education");break;
                    case "social_networks":keytext=qsTr("social networks");break;
                    case "homepage":keytext=qsTr("homepage");break;
                    default:keytext=key;
                }
                profiletext=profiletext+("<b>"+keytext+": </b> "+(pobject[key])+"<br>");
            }
        }
        callback(profiletext)
    }

    MButton {
        id: update
        anchors.top: parent.top
        anchors.topMargin: mm
        anchors.right: parent.right
        text: "\uf021"
        font.pointSize: osSettings.bigFontSize
        onClicked: {
            Service.requestProfile(root.login,root.db,root,function(nc){
                root.newContacts=nc;
                root.onNewContactsChanged(nc);
                photoImage.source="";
                showProfile(function(newprofile){
                    profile=newprofile;
                    try {profileModel.clear()} catch(e){print(e)};
                    newprofile.profiles.sort(function(obj1, obj2) {
                        return obj1.profile_id - obj2.profile_id;
                    })
                    for(var i in newprofile.profiles){var obj=newprofile.profiles[i];
                        buildProfiletext(obj,function(profiletext){
                            profileModel.append({"profileid":obj.profile_id,"profiletext":profiletext})
                        })
                    }
                    photoImage.source="file://"+newprofile.friendica_owner.profile_image;
                });
            });
        }
    }


    Image {
        id: photoImage
        anchors.top: parent.top
        anchors.topMargin: mm
        anchors.left: parent.left
        width: 15*mm
        height:15*mm
        source: "file://"+profile.friendica_owner.profile_image
        onStatusChanged: if (photoImage.status == Image.Error) {source="qrc:/images/defaultcontact.jpg"}
        MouseArea{
                anchors.fill: parent
                onClicked:{
                    imagePicking=true;
                    var imagePicker = Qt.createQmlObject('import QtQuick 2.0; import "qrc:/qml/genericqml";'+
                    osSettings.imagePickQml+'{multiple: false;onReady: {photoImage.source=imageUrl;'+
                    '}}',profileTab,"imagePicker");
                     imagePicker.pickImage()
                }
        }
    }
        Rectangle{
            id:phototextRectangle
            color:"black"
            z:3
            opacity: 0.5
            width:6*mm
            height: phototext.contentHeight
            anchors.top: photoImage.top
            anchors.right: photoImage.right
        }
        Text {
            id:phototext
            z:4
            text: "\uf040"
            width:5*mm
            anchors.top: photoImage.top
            anchors.right:photoImage.right
            color: "white"
            font.pointSize: 1.2*osSettings.bigFontSize
        }

    MButton{
        id:updatebutton
        width: 8*root.fontFactor*osSettings.bigFontSize
        visible: "file://"+profile.friendica_owner.profile_image!= photoImage.source
        text:qsTr("Update")
        font.pointSize: osSettings.bigFontSize
        anchors.left: photoImage.right
        anchors.leftMargin: 0.5*mm
        anchors.topMargin: mm
        anchors.top: parent.top
        onClicked:{updateProfileImage()}
     }
     Label {
        id: namelabel
        x: mm
        width: parent.width-6*mm
        height: 3*mm
        text:(Qt.atob(profile.friendica_owner.name))+" (@"+profile.friendica_owner.screen_name+")"
        elide:Text.ElideRight
        anchors.topMargin: 0
        anchors.left: photoImage.left
        wrapMode: Text.Wrap
        color: Material.secondaryTextColor//"#303030"
        font.pointSize: osSettings.bigFontSize
        anchors.top: photoImage.bottom
        }

    ListModel{id:profileModel}
    Component{
        id:profileItem
        Rectangle{
            id:profileRect
            width:profileView.width
            color: Material.backgroundColor
            height: 5*mm+profiletextfield.height
            Text{
                y:mm
                font.pointSize: osSettings.systemFontSize
                text:"<b>"+qsTr("profile id")+": </b> "+profileid+"<br>"
                color:Material.primaryTextColor//"black"
            }
            Text{
                id:profiletextfield
                x:2*mm
                y:4.5*mm
                width:parent.width-2.5*mm
                wrapMode: Text.Wrap
                font.pointSize: osSettings.systemFontSize
                text:profiletext
                color:Material.primaryTextColor//"black"
            }
        }
    }
    Component{
        id:textcomponent
        Text{
            id:namelabeltext
            color:Material.primaryTextColor
            width: namelabelflickable.width
            height: implicitHeight
            font.pointSize: osSettings.bigFontSize
            textFormat:Text.RichText
            wrapMode: Text.Wrap
            text:"<b>"+qsTr("Description")+": </b> "+(Qt.atob(profile.friendica_owner.description))+"<br> <b>"+qsTr("Location")+":</b> "+profile.friendica_owner.location+"<br> <b>"+qsTr("Posts")+":</b> "+profile.friendica_owner.statuses_count+
                "<br> <b>"+qsTr("URL")+":</b> <a href='"+ profile.friendica_owner.url+"'>"+profile.friendica_owner.url+"</a><br>"+
                "<b>"+qsTr("Created at")+":</b> "+createdAtDate.toLocaleString(Qt.locale())
            onLinkActivated: {
               Qt.openUrlExternally(link)}
        }
    }

       ScrollView{
           ScrollBar.horizontal.policy: ScrollBar.AlwaysOff
           id:namelabelflickable
           anchors.top: namelabel.bottom
           anchors.topMargin: 2*mm
           width: parent.width-mm
           height:parent.height-22*mm//friendsTabView.height-45*mm
           x: mm
           clip:true

           ListView {
             id: profileView
             header:textcomponent
             spacing: 0
             model: profileModel
             delegate: profileItem
            }
        }


    Component.onCompleted: {
        profile.profiles.sort(function(obj1, obj2) {
            return obj1.profile_id - obj2.profile_id;
        })
        for(var i in profile.profiles){var obj=profile.profiles[i];
            buildProfiletext(obj,function(profiletext){
                profileModel.append({"profileid":obj.profile_id,"profiletext":profiletext})
            })
        }
    }
}