var Clay = require('pebble-clay');
var clayConfig = require('./config');
var clay = new Clay(clayConfig);

var sid;
var status;

function authenticate() {
    var response;
    sid = "";
    console.log('---- authenticate');
    console.log('-- ' + localStorage.getItem('username'));
    console.log('-- ' + localStorage.getItem('password'));
    console.log('-- ' + localStorage.getItem('server'));
    if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
        var username = localStorage.getItem('username');
        var password = localStorage.getItem('password');
        var server = localStorage.getItem('server');
        var url = server + "/webapi/auth.cgi?api=SYNO.API.Auth&method=Login&version=2&account=" + username + "&passwd=" + password + "&session=SurveillanceStation&format=sid";
        var xhr = new XMLHttpRequest();

        xhr.open("GET", url, false);
        xhr.send();

        if (xhr.status == 200) {
            response = JSON.parse(xhr.responseText);
            if (response.success == true) {
                sid = response.data.sid;
            }
        } else {
            console.log('------Request returned error code ' + xhr.status.toString());
        }

        if (sid != "") {
            auth = "";
            message = "Welcome to Syno Cam Switch ! ready & authenticated";

            // Build message
            var dict = {
                'auth': message,
            };

            // Send the message
            Pebble.sendAppMessage(dict, function(e) {
                console.log('sent');
            }, function() {
                console.log('failed');
            });

        }

    } else {
        Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
    }
}

function get_status() {
    var response;

    if (sid != "") {
        status = "";
        console.log('---- get_status');
        if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
            var username = localStorage.getItem('username');
            var password = localStorage.getItem('password');
            var server = localStorage.getItem('server');
            url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;
            var xhr = new XMLHttpRequest();

            xhr.open("GET", url, false);
            xhr.send();

            if (xhr.status == 200) {
                response = JSON.parse(xhr.responseText);
                if (response.success == true) {
                    status = response.data.on;
                    var message;
                    switch (status) {
                        case true:
                            message = "Your Home mode is ON";
                            break;
                        case false:
                            message = "Your Home mode is OFF";
                            break;
                        default:
                            message = "home mode is unknown !";
                    }
                    // Build message
                    var dict = {
                        'status': message,
                    };

                    // Send the message
                    Pebble.sendAppMessage(dict, function(e) {
                        console.log('sent');
                    }, function() {
                        console.log('failed');
                    });
                }
            } else {
                console.log('------Request returned error code ' + xhr.status.toString());
            }
        } else {
            Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
        }
    }

}


function switch_home(bool) {
    var response;
    console.log('---- authenticate');
    if (sid != "") {
        status = "";
        console.log('---- get_status');
        if (localStorage.getItem('username') && localStorage.getItem('password') && localStorage.getItem('server')) {
            var username = localStorage.getItem('username');
            var password = localStorage.getItem('password');
            var server = localStorage.getItem('server');
            var xhr = new XMLHttpRequest();

            url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=GetInfo&_sid=" + sid;

            xhr.open("GET", url, false);
            xhr.send();

            if (xhr.status == 200) {
                response = JSON.parse(xhr.responseText);
                if (response.success == true) {
                    status = response.data.on;
                    console.log('------ status:' + status);
                    var message;
                    var dict;
                    if (status != bool) {
                        console.log('---- switching home mode to ' + bool);
                        url = server + "/webapi/entry.cgi?api=SYNO.SurveillanceStation.HomeMode&version=1&method=Switch&on=" + bool + "&_sid=" + sid;

                        xhr.open("GET", url, false);
                        xhr.send();

                        if (xhr.status == 200) {
                            response = JSON.parse(xhr.responseText);
                            if (response.success == true) {
                                status = bool;
                                switch (status) {
                                    case true:
                                        message = "You just set Home mode ON";
                                        break;
                                    case false:
                                        message = "You just set Home mode OFF";
                                        break;
                                    default:
                                        message = "something happened, try again !";
                                }
                                // Build message
                                dict = {
                                    'status': message,
                                };

                                // Send the message
                                Pebble.sendAppMessage(dict, function(e) {
                                    console.log('sent');
                                }, function() {
                                    console.log('failed');
                                });
                            }
                        } else {
                            console.log('------Request returned error code ' + xhr.status.toString());
                        }
                    } else {
                        console.log('---- nothign to do, status already ' + status);
                        switch (status) {
                            case true:
                                message = "Your Home Mode is already ON";
                                break;
                            case false:
                                message = "Your Home Mode is already OFF";
                                break;
                            default:
                                message = "something happened, try again !";
                        }
                        // Build message
                        dict = {
                            'status': message,
                        };

                        // Send the message
                        Pebble.sendAppMessage(dict, function(e) {
                            console.log('sent');
                        }, function() {
                            console.log('failed');
                        });
                    }
                }
            } else {
                console.log('------Request returned error code ' + xhr.status.toString());
            }
        } else {
            Pebble.showSimpleNotificationOnPebble("DSCam H-S", "You need to set your Synology account and server.");
        }
    }

}

// Get JS readiness events
Pebble.addEventListener('ready', function(e) {
    console.log('PebbleKit JS is ready');
    // Update Watch on this
    Pebble.sendAppMessage({ 'JSReady': 1 });
});
/*
// Get AppMessage events
Pebble.addEventListener('appmessage', function(e) {
  // Get the dictionary from the message
  var dict = e.payload;
  console.log(dict[0].toString());
  switch (dict[0]) {
    case 'auth':
      authenticate();
      break;
    case 'get':
      get_status();
      break;
    case 'home_on':
      switch_home(true);
      break;
    case 'home_off':
      switch_home(false);
      break;
    default:
      console.log('Sorry. I don\'t understand your request :'+ dict[0]);
  }
  
});
*/