Index: /trunk/zpush/backend/expresso/providers/calendarProvider.php
===================================================================
--- /trunk/zpush/backend/expresso/providers/calendarProvider.php	(revision 7671)
+++ /trunk/zpush/backend/expresso/providers/calendarProvider.php	(revision 7687)
@@ -4,4 +4,5 @@
 require_once EXPRESSO_PATH . '/prototype/api/controller.php';
 require_once EXPRESSO_PATH . '/prototype/api/config.php';
+require_once EXPRESSO_PATH . '/prototype/modules/calendar/constants.php';
 
 use prototype\api\Config as Config;
@@ -162,5 +163,5 @@
         $messages = array();
 
-        $sql = 'SELECT calendar_object.last_update , calendar_object.cal_uid FROM calendar_signature , calendar , calendar_to_calendar_object, calendar_object WHERE calendar_signature.id = '.$idNumber.' AND calendar_signature.calendar_id = calendar.id AND calendar_to_calendar_object.calendar_id = calendar.id AND calendar_to_calendar_object.calendar_object_id = calendar_object.id  AND calendar_object.last_update > '.$cutoffdate;
+        $sql = 'SELECT calendar_object.last_update , calendar_object.cal_uid FROM calendar_signature , calendar , calendar_to_calendar_object, calendar_object WHERE calendar_signature.id = '.$idNumber.' AND calendar_signature.calendar_id = calendar.id AND calendar_to_calendar_object.calendar_id = calendar.id AND calendar_to_calendar_object.calendar_object_id = calendar_object.id  AND calendar_object.last_update > '. $cutoffdate . '000';
 
         $rs = Controller::service('PostgreSQL')->execSql($sql);
@@ -222,7 +223,6 @@
         }
 
-        $message->sensitivity = 0; // 0 - Normal
+        $message->sensitivity = 0; // 0 - Normal,
         $message->alldayevent = (int)$schedulable['allDay']; // (0 - NÃ£o(default), 1- Sim)
-        $message->busystatus = 2; // 2 - Ocupado
         $message->timezone = base64_encode($this->_getSyncBlobFromTZ($this->_getGMTTZ()));
 
@@ -241,6 +241,25 @@
                     $message->organizername = mb_convert_encoding($participant['user']['name'], 'UTF-8' , 'UTF-8,ISO-8859-1');
                     $message->organizeremail = mb_convert_encoding($participant['user']['mail'], 'UTF-8' , 'UTF-8,ISO-8859-1');
-
-                    if(isset($participant['alarms'][0]))
+                }
+                else
+                {
+                    $attendee = new SyncAttendee();
+                    $attendee->name =  mb_convert_encoding($participant['user']['name'], 'UTF-8' , 'UTF-8,ISO-8859-1');
+                    $attendee->email = mb_convert_encoding($participant['user']['mail'], 'UTF-8' , 'UTF-8,ISO-8859-1');
+                    $message->attendees[] = $attendee;
+                }
+
+                if($participant['user']['id'] == $this->_uidnumber  )
+                {
+                    if($participant['isOrganizer'] == 1 || strpos($participant['acl'] ,'w') !== false) // Caso ele seja organizador ou tenha permisÃ£o de editar o evento
+                    {
+                        $message->meetingstatus = 0;
+                    }
+                    else
+                    {
+                        $message->meetingstatus = 3;
+                    }
+
+                    if(isset($participant['alarms'][0]) )
                     {
                         switch($participant['alarms'][0]['unit'])
@@ -260,13 +279,21 @@
                     }
 
+                    switch($participant['status'])
+                    {
+                        case STATUS_ACCEPTED:
+                            $message->busystatus = 2;
+                           break;
+                        case STATUS_TENTATIVE:
+                            $message->busystatus = 1;
+                            break;
+                        case STATUS_DECLINED:
+                            $message->busystatus = 3;
+                            break;
+                        case STATUS_UNANSWERED:
+                            $message->busystatus = 0;
+                            break;
+                    }
+
                 }
-                else
-                {
-                    $attendee = new SyncAttendee();
-                    $attendee->name =  mb_convert_encoding($participant['user']['name'], 'UTF-8' , 'UTF-8,ISO-8859-1');
-                    $attendee->email = mb_convert_encoding($participant['user']['mail'], 'UTF-8' , 'UTF-8,ISO-8859-1');
-                    $message->attendees[] = $attendee;
-                }
-                //TODO: Verificar status dos convidados
             }
         }
@@ -333,4 +360,6 @@
             $message->recurrence = $recur;
         }
+
+
         return $message;
     }
@@ -386,16 +415,96 @@
     {
 
-
-       return $idMessage ? $this->updateEvent($folderid, $idMessage, $message) : $this->createEvent($folderid, $idMessage, $message);
-    }
-
-    private function updateEvent($folderid, $idMessage, $message)
-    {
         $idNumber = (int)str_replace('calendar' , '' , $folderid);
         $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
         $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $calendarSignature['calendar'] ));
 
-        $schedulable = Controller::find(array('concept' => 'schedulable'), null , array('deepness'=> 2 , 'filter' => array( '=' , 'uid' , $idMessage)));
-        $schedulable = $schedulable[0];
+        if($idMessage)
+        {
+            $schedulable = Controller::find(array('concept' => 'schedulable'), null , array('deepness'=> 2 , 'filter' => array( '=' , 'uid' , $idMessage)));
+            $schedulable = $schedulable[0];
+
+
+            foreach($schedulable['participants'] as $i => $v)
+            {
+                if($v['user']['id'] == $this->_uidnumber )
+                {
+                    if(strpos($v['acl'] ,'w') !== false) //Caso o usuario tenha permissÃ£o de editar o evento
+                    {
+                        return  $this->updateEvent($folderid, $idMessage, $message , $calendar ,$schedulable);
+                    }
+                    else
+                    {
+                        $interation = array();
+
+                        if(isset($message->reminder) && $message->reminder > 0)
+                        {
+                            $alarm = array();
+                            $alarmID = mt_rand() . '6(Formatter)';
+                            $alarm['type'] = 'alert';
+                            $alarm['time'] = $message->reminder;
+                            $alarm['unit'] = 'm';
+                            $alarm['participant'] = $v['id'];
+                            $alarm['schedulable'] = $schedulable['id'];
+                            $interation['alarm://' . $alarmID ] = $alarm;
+
+                        }
+
+                        $status  = $this->formatBusy($message->busystatus);
+
+                        if($status == STATUS_DECLINED ) //Caso ele nÃ£o seja dono do evento e recusou o convite deletar o evento da sua agenda.
+                        {
+                            Controller::deleteAll(array('concept' => 'calendarToSchedulable' ) , false , array('filter' => array('AND', array('=','calendar',$calendarSignature['calendar']), array('=','schedulable',$schedulable['id']))));
+                        }
+
+                        $v['status'] = $status;
+
+                        $interation['participant://' . $v['id'] ] = $v;
+
+                        ob_start();
+                        $args = $interation;
+                        include EXPRESSO_PATH.'/prototype/Sync.php';
+                        ob_end_clean();
+
+                    }
+                }
+            }
+            return $this->StatMessage($folderid, $message->uid);
+        }
+        else
+        {
+            if (!$schedulable = $this->_getSchedulable($message->uid))
+                return  $this->createEvent($folderid, $idMessage, $message ,$calendar);
+            else{
+                $links = Controller::read(array('concept' => 'calendarToSchedulable'), array('id'), array('filter' =>
+                array('AND',
+                    array('=', 'calendar', $calendar['id']),
+                    array('=', 'schedulable', $schedulable['id'])
+                )));
+
+                if(!$links &&  !isset($links[0]))
+                    Controller::create(array('concept' => 'calendarToSchedulable'), array('calendar' => $calendar['id'], 'schedulable' => $schedulable['id']));
+
+                foreach($schedulable['participants'] as $i => $v)
+                {
+                    if($v['user']['id'] == $this->_uidnumber)
+                    {
+                        Controller::update(array('concept' => 'participant','id' => $v['id']), array('status' => $this->formatBusy($message->busystatus ) ));
+                    }
+                }
+
+                return $this->StatMessage($folderid, $message->uid);
+            }
+        }
+
+    }
+
+    private function _getSchedulable($uid) {
+        $schedulable = Controller::find(array('concept' => 'schedulable'), false, array('filter' => array('=', 'uid', $uid), 'deepness' => 2));
+        return (isset($schedulable[0])) ? $schedulable[0] : false;
+    }
+
+    private function updateEvent($folderid, $idMessage, $message , $calendar ,$schedulable )
+    {
+
 
         $tz_CEL = $this->_getTZFromSyncBlob(base64_decode($message->timezone));
@@ -584,4 +693,12 @@
         }
 
+        foreach($schedulable['participants'] as $i => $v)
+        {
+            if($v['user']['id'] == $this->_uidnumber )
+            {
+               $schedulable['participants'][$i]['status'] = $this->formatBusy($message->busystatus);
+            }
+        }
+
         unset($schedulable['repeat']);
 
@@ -596,11 +713,6 @@
     }
 
-    private function createEvent($folderid, $idMessage, $message)
-    {
-        $idNumber = (int)str_replace('calendar' , '' , $folderid);
-        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
-        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $calendarSignature['calendar'] ));
-
-
+    private function createEvent($folderid, $idMessage, $message , $calendar)
+    {
         $tz_CEL = $this->_getTZFromSyncBlob(base64_decode($message->timezone));
         $GMT_CEL = -(($tz_CEL["bias"] + $tz_CEL["dstbias"]) * 60);
@@ -611,5 +723,5 @@
         $eventID = mt_rand() . '(Formatter)';
 
-        $schedulable['calendar'] = $calendarSignature['calendar'];
+        $schedulable['calendar'] = $calendar['id'];
         $schedulable['uid'] = $message->uid;
         $schedulable['summary'] = $message->subject;
@@ -664,4 +776,5 @@
             $participant['isExternal'] = 0;
             $participant['user'] = $this->_uidnumber;
+            $participant['status'] = $this->formatBusy($message->busystatus);
         }
 
@@ -754,4 +867,10 @@
                     $participant['user'] = $userID;
                     $interation['user://' . $userID] = $user;
+
+                    if($userID == $this->_uidnumber)
+                    {
+                        $participant['status'] = $this->formatBusy($message->busystatus);
+                    }
+
                 }
 
@@ -834,9 +953,38 @@
     public function DeleteMessage($folderid, $id)
     {
-        $even = Controller::find(array('concept' => 'schedulable') , false , array ( 'filter' => array('=' , 'uid' , $id ) )  );
-
-        if(is_array($even) && count($even) > 0 )
-            Controller::delete(array('concept' => 'schedulable' , 'id' => $even[0]['id']));
-
+
+        $idNumber = (int)str_replace('calendar' , '' , $folderid);
+        $calendarSignature =  Controller::read( array( 'concept' => 'calendarSignature' , 'id' => $idNumber ));
+        $even = $this->_getSchedulable($id );
+        $calendar =  Controller::read( array( 'concept' => 'calendar' , 'id' => $calendarSignature['calendar'] ));
+
+        $link = Controller::read(array('concept' => 'calendarToSchedulable'), false, array('filter' => array('AND', array('=','calendar',$calendarSignature['calendar']), array('=','schedulable',$even['id']))));
+
+        $delete = false;
+        foreach($even['participants'] as $i => $v)
+        {
+            if($v['user']['id'] == $this->_uidnumber && $v['user']['isOrganizer']  == '1')
+            {
+              $delete = true;
+            }
+        }
+
+        if( $delete === true)
+        {
+            Controller::delete(array('concept' => 'schedulable' , 'id' => $even['id']));
+        }
+        else
+        {
+            Controller::delete(array('concept' => 'calendarToSchedulable', 'id' => $link[0]['id']));
+
+            foreach($even['participants'] as $i => $v)
+            {
+                if($v['user']['id'] == $this->_uidnumber)
+                {
+                    Controller::update(array('concept' => 'participant','id' => $v['id']), array('status' => STATUS_CANCELLED ));
+                }
+            }
+
+        }
         return true;
     }
@@ -897,5 +1045,4 @@
             $_SESSION['flags']['currentapp'] = 'expressoCalendar';
 
-            Config::regSet( 'noAlarm' , true ); //Evita envio de alertas pelo expresso isto Ã© responsabilidade do cliente celular
         //----------------------------------------------------------------------------------------//
 
@@ -1044,3 +1191,26 @@
         return false;
     }
+
+
+    private function formatBusy($status)
+    {
+        switch($status)
+        {
+            case 2:
+                return STATUS_ACCEPTED;
+                break;
+            case 1:
+                return STATUS_TENTATIVE;
+                break;
+            case 3:
+                return STATUS_DECLINED;
+                break;
+            case 0:
+               return STATUS_UNANSWERED;
+                break;
+        }
+    }
+
+
+
 }
