/**
 * Created by Gayan on 12/13/15.
 */
angular.module('app.services')
  .factory('WifiService', ['$log', function ($log) {
    var unique_array = angular.fromJson('[]');

    return {
      list: function () {
        return unique_array;
      },
      connectionWifi: function (wifi_ssid) {
        $log.debug("connectionWifi " + wifi_ssid);
        WifiWizard.connectNetwork(wifi_ssid, this.win_wifi, this.fail_wifi);
      },
      disconnectWifi: function (wifi_ssid) {
        $log.debug("disconnectWifi " + wifi_ssid);
        WifiWizard.disconnectNetwork(wifi_ssid, this.win_wifi, this.fail_wifi);
      },
      win_wifi: function (e) {
        $log.debug("WifiService successfully connected");
      },

      fail_wifi: function (e) {
        $log.debug("WifiService Error");
      },

      listHandler: function (a) {
        var network_array = [];
        for (var i = 0; i < a.length; i++) {
          network_array.push(a[i].SSID);
        }

        unique_array = network_array.filter(function (elem, pos) {
          return network_array.indexOf(elem) == pos;
        });
      },

      getScanResult: function () {
        WifiWizard.getScanResults(this.listHandler, this.failNetwork);
      },

      successNetwork: function (e) {
        window.setTimeout(function () {
          this.getScanResult();
        }, 3000);
      }, failNetwork: function (e) {
        $log.debug("WifiService Network Failure" + e);
      }, getConnectedSSID: function (e) {
        return WifiWizard.getCurrentSSID(this.win_wifi, this.fail_wifi)
      }, startScan: function () {
        window.setTimeout(function () {
          WifiWizard.startScan(this.successNetwork, this.failNetwork);
        }, 1000);
      }, setWifiEnabled: function (enabled) {
         WifiWizard.setWifiEnabled(enabled, this.win_wifi, this.fail_wifi);
      }
    };
  }]);



