/**
  * Function to add or update segment
  * 
  * @param array $params
  * @return array $result
  * @throws Exception when params empty
  * @access public
  * @static
  */
 public static function add($params)
 {
     $result = array();
     $preSegment = array();
     if (empty($params)) {
         throw new Exception('Params can not be empty when adding or updating a segment', 9003);
     }
     $segment = new CRM_Contactsegment_BAO_Segment();
     if (isset($params['id'])) {
         $segment->id = $params['id'];
         // pre hook if edit
         $op = "edit";
         self::storeValues($segment, $preSegment);
         CRM_Utils_Hook::pre($op, 'Segment', $segment->id, $preSegment);
         $segment->find(true);
     } else {
         $op = "create";
     }
     $fields = self::fields();
     foreach ($params as $paramKey => $paramValue) {
         if (isset($fields[$paramKey])) {
             $segment->{$paramKey} = $paramValue;
         }
     }
     if (!$segment->name && $segment->label) {
         $segment->name = CRM_Contactsegment_Utils::generateNameFromLabel($segment->label);
     }
     $segment->save();
     if (!$segment->is_active) {
         CRM_Contactsegment_BAO_Segment::setInactive($segment->id);
     }
     // post hook
     CRM_Utils_Hook::post($op, 'Segment', $segment->id, $segment);
     self::storeValues($segment, $result);
     return $result;
 }
 /**
  * Function to save the segment
  *
  * @param $formValues
  * @access protected
  */
 protected function saveSegment($formValues)
 {
     $params = array();
     if ($formValues['segment_id']) {
         $params['id'] = $formValues['segment_id'];
     }
     $params['label'] = $formValues['segment_label'];
     $params['is_active'] = $formValues['is_active'] ? '1' : '0';
     $params['name'] = CRM_Contactsegment_Utils::generateNameFromLabel($params['label']);
     if ($this->_action == CRM_Core_Action::ADD) {
         $segmentType = key($formValues['segment_type_list']);
     } else {
         if ($formValues['segment_parent']) {
             $segmentType = 1;
         }
     }
     switch ($segmentType) {
         case 0:
             $params['parent_id'] = NULL;
             $statusTitle = $this->_parentLabel . " saved";
             $statusMessage = $this->_parentLabel . " " . $params['label'] . " saved";
             break;
         case 1:
             $params['parent_id'] = $formValues['segment_parent'];
             $statusTitle = $this->_childLabel . " saved";
             $statusMessage = $this->_childLabel . " " . $params['label'] . " from " . $this->_parentLabel . " " . $this->getSegmentParentLabel($formValues['segment_parent']) . " saved";
             break;
     }
     $this->_segment = civicrm_api3('Segment', 'Create', $params);
     $session = CRM_Core_Session::singleton();
     $session->setStatus($statusMessage, $statusTitle, "success");
 }