<?php

  /**
   * Framework level homescreen tabs manager implementation
   * 
   * @package angie.frameworks.homescreens
   * @subpackage models
   */
  abstract class FwHomescreenTabs extends BaseHomescreenTabs {
  
    /**
     * Return homescreen tabs that belong to a given homescreen
     * 
     * @param Homescreen $homescreen
     * @return DBResult
     */
    static function findByHomescreen(Homescreen $homescreen) {
      return HomescreenTabs::find(array(
        'conditions' => array('homescreen_id = ?', $homescreen->getId()), 
        'order' => 'position', 
      ));
    } // findByHomescreen
    
    /**
     * Return next home screen tab position by home screen
     * 
     * @param Homescreen $homescreen
     * @return integer
     */
    static function getNextPosition(Homescreen $homescreen) {
      return ((integer) DB::executeFirstCell('SELECT MAX(position) FROM ' . TABLE_PREFIX . 'homescreen_tabs WHERE homescreen_id = ?', $homescreen->getId())) + 1;
    } // getNextPosition
    
    /**
     * Delete widgets by home screen
     * 
     * @param Homescreen $homescreen
     * @return boolean
     */
    static function deleteByHomescreen(Homescreen $homescreen) {
      return DB::execute('DELETE FROM ' . TABLE_PREFIX . 'homescreen_tabs WHERE homescreen_id = ?', $homescreen->getId());
    } // deleteByHomescreen

    /**
     * Remove all home screen tab types when module is uninstalled
     *
     * @param AngieModule $module
     */
    static function deleteByModule(AngieModule $module) {
      $tab_types = array();

      $d = dir($module->getPath() . '/models/homescreen_tabs');
      if($d) {
        while(($entry = $d->read()) !== false) {
          $class_name = str_ends_with($entry, '.class.php') ? str_replace('.class.php', '', $entry) : null;

          if($class_name) {
            $tab_types[] = $class_name;
          } // if
        } // if

        $d->close();
      } // if

      if (count($tab_types)) {
        return DB::execute("DELETE FROM " . TABLE_PREFIX . "homescreen_tabs WHERE type IN (?)", $tab_types);
      } // if
    } // deleteByModule
    
  }