'use strict';
/**
 * @ngdoc service
 * @name Devices
 * @description
 *  device 관련 기능
 */
app.service('Devices', function ($http, $q, Rooms) {

  this.icons = [];
  this.menuBtnPages = [];
  this.hardBtnPages = [];
  this.currentData = {};
  this.functions = [];
  this.currentDevice = {};

  /**
   * Learn codes from an IR remote 메뉴에 나오는 hard button 목록 설정
   * @memberof Devices
   */
  this.initHardBtnPages = function() {
    this.hardBtnPages = [{btns:[{name:'VOL +',id:275},{name:'PREV CH',id:278},{name:'CH +',id:279},{name:'VOL -',id:276},{name:'MUTE',id:277},{name:'CH -',id:280}]},{btns:[{name:'MENU',id:305},{name:'UP',id:322},{name:'GUIDE',id:304},{name:'LEFT',id:320},{name:'SELECT',id:324},{name:'RIGHT',id:321},{name:'INFO',id:306},{name:'DOWN',id:323},{name:'EXIT',id:307}]},{btns:[{name:'SKIP -',id:295},{name:'PLAY',id:288},{name:'SKIP +',id:294},{name:'REW',id:292},{name:'PAUSE',id:291},{name:'FWD',id:293},{name:'STOP',id:289},{name:'REC',id:296},{name:'YELLOW',id:548},{name:'BLUE',id:549},{name:'RED',id:550},{name:'GREEN',id:551}]},{btns:[{name:'1',id:337},{name:'2',id:338},{name:'3',id:339},{name:'4',id:340},{name:'5',id:341},{name:'6',id:342},{name:'7',id:343},{name:'8',id:344},{name:'9',id:345},{name:'/',id:346},{name:'0',id:336},{name:'ENT',id:348}]}];

  };

  /**
   * icons 저장
   * @memberof Devices
   * @param {Array} icons icons array
   */
  this.setIcons = function(icons) {
    this.icons = icons;
  };

  /**
   * icons 얻기
   * @memberof Devices
   * @returns {Array} icons array
   */
  this.getIcons = function() {
    return this.icons;
  };

  /**
   * icon 목록이 있는 json 파일로부터 데이터 얻기
   * @memberof Devices
   * @returns {Promise} Future object
   */
  this.getInfoJson = function() {
    return $http.get('/file/images/device_icons/info.json');
  };

  /**
   * device data 저장
   * @memberof Devices
   * @param {Object} data device data
   */
  this.setCurrentData = function(data) {
    this.currentData = data;
  };

  /**
   * device data 얻기
   * @memberof Devices
   * @returns {Object}
   */
  this.getCurrentData = function() {
    return this.currentData;
  };

  /**
   * add device 하는 중 device 임시 저장
   * @memberof Devices
   * @param {Object} data device data
   */
  this.setCurrentDevice = function(device) {
    this.currentDevice = device;
  };

  /**
   * add device 하는 중 임시 device 데이터 얻기
   * @memberof Devices
   * @returns {Object}
   */
  this.getCurrentDevice = function() {
    return this.currentDevice;
  };

  this.setMenuBtnPages = function(pages) {
    this.menuBtnPages = pages;
  };

  this.getMenuBtnPages = function() {
    return this.menuBtnPages;
  };

  this.setHardBtnPages = function(pages) {
    this.hardBtnPages = pages;
  };

  this.getHardBtnPages = function() {
    return this.hardBtnPages;
  };


  this.initFunctions = function() {
     this.functions = [];
  };

  this.setFunctions = function(id, funcs) {

    for(var index = 0; index < this.functions.length; index++) {
      if(this.functions[String(id)] !== undefined) {
        this.functions[String(id)] = angular.copy(funcs);
        return;
      }
    }

    this.functions[String(id)] = angular.copy(funcs);
  };

  this.getFunctions = function(id) {
    if(this.functions[String(id)] !== undefined) {
      return this.functions[String(id)];
    }
    return null;
  };


  this.fetchFunctions = function(roomId, deviceId) {
    var d = $q.defer();
    $http.post('/urcassistant/api/device/get_con_dev/' + roomId + '/' + deviceId).success(function(response) {
      if (response.result) {
        d.resolve(response.data);
      } else {
        d.reject(response.error);
      }
    }).error(function(error) {
      d.reject(error);
    });
    return d.promise;
  };


  this.fetchPunchDevice = function(roomId, deviceId) {

    var d = $q.defer();
    $http.post('/urcassistant/api/device/get_punch/' + roomId + '/' + deviceId).success(function(response) {
      if (response.result) {
        d.resolve(response.data);
      } else {
        d.reject(response.error);
      }
    }).error(function(error) {
      d.reject(error);
    });
    return d.promise;
    
  };

  this.createOne = function(roomId, data) {
    var d = $q.defer();

    $http.post('/urcassistant/api/device/create/' + roomId, data).success(function (response) {
      if (response.result) {
        d.resolve(response);
      } else {
        d.reject(response.error);
      }
    }).error(function (error) {
      d.reject(error);
    });
    return d.promise;
  };

  this.createCustomOne = function(roomId, data) {
    var d = $q.defer();

    $http.post('/urcassistant/api/device/create_custom/' + roomId, data).success(function (response) {
      if (response.result) {
        d.resolve(response);
      } else {
        d.reject(response.error);
      }
    }).error(function (error) {
      d.reject(error);
    });
    return d.promise;
  };

  this.makeBlankMenuButton = function(btnId, pgBtnIdx, props ) {
    return {  id: btnId, 
              page_btn_idx: pgBtnIdx, 
              display_text: null, 
              repeat_min: props.repeat.min, 
              repeat_macro: props.repeat.macro, 
              repeatSetting: 'default',
              room_id: props.room_id,
              device_id: props.device_id ? props.device_id : -1,
              activity: '',
              auto_wait: 0,
              edit_type: 1,
              func: null,
              hidden_option: 0,
              image_name: '',
              link_id: -1,
              macro: '',     
              popup: 0,
              press_hold: true };
  };     


  this.makeBlankMenuPage = function(props) {
    var pg = { id:0, btns: [] };

    for (var i=0, j=8192; i < 6; i++, j++) {
      pg.btns.push({  id: j,
                      page_btn_idx: i,
                      display_text: null, 
                      repeat_min: props.repeat.min,
                      repeat_macro: props.repeat.macro,
                      repeatSetting: 'default',
                      room_id: props.room_id,
                      device_id: props.device_id ? props.device_id : -1,  
                      activity: '',
                      auto_wait: 0,
                      edit_type: 1,
                      func: null,
                      hidden_option: 0,
                      image_name: '',
                      link_id: -1,
                      macro: '',     
                      popup: 0,
                      press_hold: true });
    }

    console.log(pg);
    return pg;
  };

  this.setBtnDefaults = function(button) {
    if (!button.hasOwnProperty('activity')) { button.activity = ''; }
    if (!button.hasOwnProperty('auto_wait')) { button.auto_wait = 0; }
    if (!button.hasOwnProperty('edit_type')) { button.edit_type = 1; }
    if (!button.hasOwnProperty('func')) { button.func = null; }
    if (!button.hasOwnProperty('hidden_option')) { button.hidden_option = 0; }
    if (!button.hasOwnProperty('image_name')) { button.image_name = ''; }
    if (!button.hasOwnProperty('macro')) { button.macro = ''; }
    if (!button.hasOwnProperty('link_id')) { button.link_id = -1; }
    if (!button.hasOwnProperty('popup')) { button.popup = 0; }
    if (!button.hasOwnProperty('press_hold')) { button.press_hold = true; }
  };

  this.addHardBtnProps = function (props) {
    var self = this;
    _.forEach(self.hardBtnPages, function(hardBtnPage) {
      _.forEach(hardBtnPage.btns, function(btn) {

        if (!btn.hasOwnProperty('display_text')) {
          btn.display_text = null;
          btn.repeat_min = props.repeat.min;
          btn.repeat_macro = props.repeat.macro;
          btn.repeatSetting = 'default';
          btn.device_id = props.device_id;
          btn.room_id = props.room_id;
          self.setBtnDefaults(btn);
        }
      });
    });
  };


  this.getOne = function(roomId, deviceId) {
    var deviceProps,
        self = this,
        d = $q.defer();

    
    function assignBtnFields(btn, macro, props) {
      if ( macro.hasOwnProperty('repeat_macro') && macro.hasOwnProperty('repeat_min') ) {
        _.assign(btn, { repeat_min: macro.repeat_min,
                        repeat_macro: macro.repeat_macro,
                        repeatSetting:'custom' });
      } else {
        _.assign(btn, { repeat_min: props.repeat.min,
                        repeat_macro: props.repeat.macro,
                        repeatSetting:'default' });
      }

      btn.func = _.where(props.dbCon, {'id': macro.func})[0]; 

      console.log('press_hold', macro.press_hold);
      
      if (macro.hasOwnProperty('press_hold')) {
        btn.press_hold = macro.press_hold ? true:false;
      } else {
        btn.press_hold = btn.func.press_hold ? true:false;
      }
    }

    $http.post('/urcassistant/api/device/get/' + roomId + '/' + deviceId)
    .success(function(response) {
      console.log(response);
      if (response.result) {
        self.menuBtnPages = [];
        self.initHardBtnPages();

        deviceProps = _.omit(response.data, 'pages');
        console.log(deviceProps);


        if (response.data.pages.length=== 0) {
          self.menuBtnPages.push( self.makeBlankMenuPage(deviceProps) );
          self.addHardBtnProps(deviceProps);
        } else {          
          if (response.data.pages.length === 1 && response.data.pages[0].id === -1) {
            console.log('1 page and its a hardBtnPage');
            self.menuBtnPages.push( self.makeBlankMenuPage(deviceProps) );
          }

          _.forEach(response.data.pages, function(page) {
            var pgToAdd = { btns: [] },
                pageIds;

            for (var i=0; i < 6; i++) {
              pgToAdd.btns.push({ page_btn_idx: i, display_text: null });
            }

            // Hard button manipulation

            if (page.id === -1) {
              _.forEach(page.btns, function(btn) {
                _.forEach(self.hardBtnPages, function(hardBtnPage) {
                  _.forEach(hardBtnPage.btns, function(button) {
                    if (button.id === btn.id) {
                      var macro = JSON.parse(btn.macro)[0];

                      _.assign(button, btn);
                      assignBtnFields(button, macro, deviceProps);
                      
                    }
                  });
                });
              });

              return;
            }

            pgToAdd.id = page.id;

            // Menu page button manipulation

            _.forEach(page.btns, function(btn) {
              var macro = JSON.parse(btn.macro)[0],
                  newBtn = _.clone(btn);

              assignBtnFields(newBtn, macro, deviceProps);

              pgToAdd.btns.splice(newBtn.page_btn_idx,1,newBtn);
            });

            // Filling in the rest of the page

            pageIds = _(pgToAdd.btns).pluck('id').value();
            if(pageIds.filter(Number).length < 6) {

              //Mathematical equation to get the correct starting id of the page to be added
              var min = 8192 + (pgToAdd.id * 6),
                btnId = min;
              console.log(btnId);

              for (var idx = 0; idx < 6; idx++) {
                var button = pgToAdd.btns[idx];
                button.id = btnId;
                //if there is no repeat setting on the btn then add the default
                if ( !button.hasOwnProperty('repeatSetting') ) {
                  button.repeat_min = deviceProps.repeat.min;
                  button.repeat_macro = deviceProps.repeat.macro;
                  button.repeatSetting = 'default';
                }
                if (!button.hasOwnProperty('room_id')) { button.room_id = roomId; }
                if (!button.hasOwnProperty('device_id')) { button.device_id = deviceId; }     
                
                self.setBtnDefaults(button);

                btnId++;
              }
            }

            self.menuBtnPages.push({ id: pgToAdd.id , btns: pgToAdd.btns });
          });

          self.addHardBtnProps(deviceProps);
        }


        d.resolve(deviceProps);
      } else {
        d.reject( response.error);
      }
    })
    .error(function(error) {
      alert('Please try again');
      d.reject(error);
    });
    return d.promise;

  };



  this.storeOne = function(roomId, deviceId, data) {
    var d = $q.defer();
    $http.post('/urcassistant/api/device/store/' + roomId + '/' + deviceId, data).success(function (response) {
      if (response.result) {
        d.resolve(response.result);
      } else {
        d.reject(response.error);
      }
    }).error(function () {
      d.reject(error);
    });
    return d.promise;
  };

});
