/**
 * Created by Denis on 19/06/2014.
 */
define(['jquery', 'backbone'],
        function ($, Backbone) {

            var Profile = {
                _loadme: function () {
                    this.data.name = this.getName();
                    this.data.gender = this.getGender();
                    if (this.isConnected()) {
                        if (this.data.type == null)
                            this.loadProfile();
                    }
                    return this;
                },
                dataloaded: false,
                data: {
                    "name": null,
                    "email": null,
                    "gender": null,
                    "tema": 'd',
                    "risRic": '10',
                    "type": null,
                    "picture": null,
                    "isSpacc": 0,
                    "dataSpacc": {
                        "stato": null,
                        "provincia": null,
                        "comune": null,
                        "cap": null,
                        "note": null,
                        "tipopm": null,
                        "privacy": 0,
                        "long": null,
                        "lat": null
                    }
                },
                isConnected: function () {
                    return this.getKeySave() != "null" &&
                            this.getKeySave() != null &&
                            this.getKeySave() != "undefined" &&
                            this.getKeySave() != undefined;
                },
                setPictureEvent: null,
                setPicture: function (val) {
                    this.data.picture = val;
                    if (this.setPictureEvent)
                        this.setPictureEvent(val);
                },
                loadProfile: function (successFn) {
                    this._loadProfile(this.getKeySave(), successFn);
                },
                _loadProfile: function (keyStore, successFn) {
                    if (this.dataloaded) {
                        if (successFn)
                            successFn(retBool);
                        return;
                    }
                    //var keyStore = this.getKeySave();
                    var self = this;
                    var retBool = false;
                    var resp = $.ajax({
                        url: myManifest.Settings.DefaultURL + "/api/profile/" + keyStore,
                        //dataType: "json",
                        //async: false,
                        type: 'GET',
                        success: function (response) {
                            if (response.length > 0)
                            {
                                self.dataloaded = true;
                                self.data.name = unescape(response[0].Name);
                                self.data.email = response[0].Email;
                                self.data.gender = response[0].Gender;
                                self.data.tema = response[0].TemaUI;
                                self.data.risRic = response[0].RisultatiRicerca;
                                self.data.type = response[0].TipoAccesso;
                                self.setKeySave(keyStore);
                                self.setName(self.data.name);
                                self.setGender(self.data.gender);
                                self.data.isSpacc = response[0].bSpacciatore;
                                self.data.dataSpacc.stato = response[0].Stato;
                                self.data.dataSpacc.provincia = unescape(response[0].Provincia);
                                self.data.dataSpacc.comune = unescape(response[0].Comune);
                                self.data.dataSpacc.cap = response[0].Cap;
                                self.data.dataSpacc.privacy = response[0].bPrivacy;
                                self.data.dataSpacc.tipopm = response[0].TipoPM;
                                self.data.dataSpacc.note = unescape(response[0].Note);
                                self.data.dataSpacc.lat = response[0].Latitudine;
                                self.data.dataSpacc.long = response[0].Longitudine;
                                retBool = true;

                                switch (self.data.type)
                                {
                                    case "facebook":
                                        img = "https://graph.facebook.com/" + keyStore + "/picture?type=normal";
                                        self.setPicture(img);
                                        break;
                                    case "google":
                                        var resp = $.ajax({
                                            url: "https://www.googleapis.com/plus/v1/people/" + keyStore + "?fields=image&key=" + myManifest.getGPublicApiKey(),
                                            //dataType: "json",
                                            //async: false,
                                            type: 'GET',
                                            success: function (resp) {
                                                self.setPicture(resp.image.url.replace("?sz=50", "?sz=150"));
                                            }
                                        });
                                        break;
                                }
                            }
                            if (successFn)
                                successFn(retBool);
                        }
                    });
                },
                resetProfile: function(){
                    this.data.name = null;
                    this.data.email = null;
                    this.data.gender = null;
                    this.data.type = null;
                    this.data.picture = null;
                    this.data.tema = 'd';
                    this.data.risRic = '10';
                    this.data.isSpacc = 0;
                    this.data.dataSpacc.stato = null;
                    this.data.dataSpacc.provincia = null;
                    this.data.dataSpacc.comune = null;
                    this.data.dataSpacc.cap = null;
                    this.data.dataSpacc.tipopm = null;
                    this.data.dataSpacc.note = null;
                    this.data.dataSpacc.privacy = 0;
                    this.data.dataSpacc.long = null;
                    this.data.dataSpacc.lat = null;
                    this.setKeySave(null);
                    this.setName("");
                    this.setGender("");
                    window.localStorage.setItem("hello", null);
                },
                _getVal: function (key) {
                    return window.localStorage.getItem(key);
                },
                _setVal: function (key, val) {
                    window.localStorage.setItem(key, val);
                },
                getKeySave: function () {
                    return this._getVal("KeySave");
                },
                setKeySave: function (val) {
                    this._setVal("KeySave", val);
                },
                getName: function () {
                    return this._getVal("userName");
                },
                setName: function (val) {
                    this._setVal("userName", val);
                },
                getGender: function () {
                    return this._getVal("userGender");
                },
                setGender: function (val) {
                    this._setVal("userGender", val);
                },
                isGPlusConnected: function () {
                    if (this.data.type === "google")
                        return true;
                    return false;
                },
                isFbConnected: function () {
                    if (this.data.type === "facebook")
                        return true;
                    return false;
                },
                addRicettaBloccoNote: function (ricetta_id, successFn) {
                    var sendobj = {
                        "ricetta_id": ricetta_id,
                        "keyStore": this.getKeySave()
                    };

                    $.ajax({
                        url: myManifest.Settings.DefaultURL + "/api/profile/ricetta",
                        //dataType: "json",
                        type: 'POST',
                        data: {dataPair: JSON.stringify(sendobj)},
                        success: function (msg) {
                            if (successFn)
                                successFn(msg);
                        }
                    });
                },
                removeRicettaBloccoNote: function (ricetta_id, successFn) {
                    $.ajax({
                        url: myManifest.Settings.DefaultURL + "/api/profile/" + this.getKeySave() + "/ricetta/" + ricetta_id,
                        //dataType: "json",
                        type: 'DELETE',
                        success: function (msg) {
                            if (successFn)
                                successFn(msg);
                        }
                    });
                },
                existRicettaBloccoNote: function (ricettaID, successFn) {
                    $.ajax({
                        url: myManifest.Settings.DefaultURL + "/api/profile/" + this.getKeySave() + "/ricetta/" + ricettaID,
                        //dataType: "json",
                        type: 'GET',
                        success: function (msg) {
                            if (successFn)
                                successFn(msg);
                        }
                    });
                },
                createProfile: function (keyStore, typeProfile, name, email, gender, successFn) {
                    this.data.type = typeProfile;
                    this.data.name = name;
                    this.data.email = email;
                    this.data.gender = gender;
                    this.setKeySave(keyStore);

                    window.localStorage.removeItem("risRic");
                    window.localStorage.removeItem("tema");

                    var sendobj = {
                        "keyStore": this.getKeySave(),
                        "name": escape(this.data.name),
                        "email": this.data.email,
                        "gender": this.data.gender,
                        "tema": this.data.tema,
                        "risRic": this.data.risRic,
                        "type": this.data.type
                    };

                    $.ajax({
                        url: myManifest.Settings.DefaultURL + "/api/profile",
                        //dataType: "json",
                        type: 'POST',
                        data: {dataPair: JSON.stringify(sendobj)},
                        success: function (msg) {
                            if (successFn)
                                successFn(msg);
                        }
                    });
                },
                updateProfile: function (successFn) {
                    if (this.isConnected()) {
                        var sendobj = {
                            "keyStore": this.getKeySave(),
                            "tema": this.data.tema,
                            "risRic": this.data.risRic,
                            "type": this.data.type,
                            "email": this.data.email,
                            "isSpacc": this.data.isSpacc,
                            "stato": this.data.dataSpacc.stato,
                            "prov": escape(this.data.dataSpacc.provincia),
                            "comune": escape(this.data.dataSpacc.comune),
                            "cap": this.data.dataSpacc.cap,
                            "tipopm": this.data.dataSpacc.tipopm,
                            "note": escape(this.data.dataSpacc.note),
                            "privacy": this.data.dataSpacc.privacy,
                            "lng": this.data.dataSpacc.long,
                            "lat": this.data.dataSpacc.lat
                        };

                        $.ajax({
                            url: myManifest.Settings.DefaultURL + "/api/profile",
                            //dataType: "json",
                            type: 'PUT',
                            data: {dataPair: JSON.stringify(sendobj)},
                            success: function (msg) {
                                if (successFn)
                                    successFn(msg);
                            }
                        });
                    }
                    else
                    {
                        window.localStorage.setItem("risRic", this.data.risRic);
                        window.localStorage.setItem("tema", this.data.tema);
                    }
                }
            };
            return Profile._loadme();
        });