<?php

//        # Copyright (C) 2012-2013 GNU remotecontrol authors.
//        #
//        # This program is free software: you can redistribute it and/or modify
//        # it under the terms of the GNU Affero General Public License as
//        # published by the Free Software Foundation, either version 3 of the
//        # License, or (at your option) any later version.
//        #
//        # This program is distributed in the hope that it will be useful,
//        # but WITHOUT ANY WARRANTY; without even the implied warranty of
//        # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//        # GNU Affero General Public License for more details.
//        #
//        # You should have received a copy of the GNU Affero General Public License
//        # along with this program.  If not, see <http://www.gnu.org/licenses/>.

    class ResourceCollection extends ArrayObject
    {
        // Constructor
        public function __construct($loadData, $code, $useSortOrder = null, $depth = null, $onlyAtLevel = null)
        {
            if($loadData)
            {
                    $this->Load($code, $useSortOrder, $depth, $onlyAtLevel);
            }
        }

        // Methods
        public function FindResourceByCode($code)
        {
                foreach($this as $res)
                {
                        if($res->Code == $code)
                        {
                                return $res;
                        }
                }

                return null;
        }

        protected function Load($code, $useSortOrder, $depth, $onlyAtLevel)
        {
                if ($code == 'All')
                {
                    $this->LoadAll();

                    return;
                }

                $dataAccess = new MySqlDataAccess(Common::ConnectionString);
                $dataAccess->Command->CommandType = CommandType::StoredProcedure;

                $langcode = 'en';

                if (isset($_SESSION['User']))
                {
                    $langcode = $_SESSION['User']->Language->Code;
                }
                if (!$langcode) {
                    $langcode = 'en';
                }

                $useSortOrder2 = 'null';

                if ($useSortOrder === true)
                {
                    $useSortOrder2 = 1;
                }
                elseif ($useSortOrder === false)
                {
                    $useSortOrder2 = 0;
                }

                $depth2 = ($depth === null) ? 'null' : $depth;

                $onlyAtLevel2 = 'null';

                if ($onlyAtLevel === true)
                {
                    $onlyAtLevel2 = 1;
                }
                elseif ($onlyAtLevel === false)
                {
                    $onlyAtLevel2 = 0;
                }

                $dataAccess->Command->CommandText = "CALL sp_Resources_Load_By_Parent_Code('$langcode', '$code', $useSortOrder2, $depth2, $onlyAtLevel2)";
                $dataAccess->GetData();

                if($dataAccess->ResultSet)
                {
                        while($row = $dataAccess->ResultSet->fetch_assoc())
                        {
                                $this->append(new Resource($row['ResourceID'], $row['Code'], $row['Value'], $row['DropDownItemValue'], $row['StyleClass'], $row['SortOrder'], $row['LFT'], $row['RGT']));
                        }
                }

                $dataAccess->Cleanup();
        }

        private function LoadAll()
        {
            $dataAccess = new MySqlDataAccess(Common::ConnectionString);
            $dataAccess->Command->CommandType = CommandType::StoredProcedure;

            $dataAccess->Command->CommandText = "CALL sp_Resources_Load_All()";
            $dataAccess->GetData();

            if($dataAccess->ResultSet)
            {
                    while($row = $dataAccess->ResultSet->fetch_assoc())
                    {
                            $this->append(new Resource($row['ResourceID'], $row['Code'], $row['Value'], $row['DropDownItemValue'], $row['StyleClass'], $row['SortOrder'], $row['Page'], $row['LFT'], $row['RGT']));
                    }
            }

            $dataAccess->Cleanup();
        }

		public function Translate($to)
        {

            try
            {

                //Client ID of the application.
                $clientID = 'GNURC';

                //Client Secret key of the application.
                $clientSecret = 'GCDmHUnpS+h+qXKYzgg2tfXVJehZyiCGKPSDrEo2Moo=';

                //OAuth Url.
                $authUrl = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13/';

                //Application Scope Url
                $scopeUrl = 'http://api.microsofttranslator.com';

                //Application grant type
                $grantType = 'client_credentials';

                //Create the AccessTokenAuthentication object.
                $authObj = new AccessTokenAuthentication();

                //Get the Access token.
                $accessToken = $authObj->getTokens($grantType, $scopeUrl, $clientID, $clientSecret, $authUrl);

                //Create the authorization Header string.
                $authHeader = 'Authorization: Bearer '. $accessToken;

                //Create the Translator Object.
                $translatorObj = new HTTPTranslator();

                foreach($this as $res)
                {

                    //HTTP Translate Method URL
                    $translateMethodUrl = 'http://api.microsofttranslator.com/V2/Http.svc/Translate?text='.urlencode($res->Value).'&to='.$to;

                    //Call the curlRequest.
                    $strResponse = $translatorObj->curlRequest($translateMethodUrl, $authHeader);

                    //Interprets a string of XML into an object.
                    $xmlObj = simplexml_load_string($strResponse);

                    //Update resource value in collection
                    //$res->Value = utf8_decode($xmlObj[0]);
					$res->Value = $xmlObj[0];

               }

               $dataAccess = new MySqlDataAccess(Common::ConnectionString);
               $dataAccess->Command->CommandType = CommandType::StoredProcedure;

               foreach($this as $res)
               {
                   $newValue = str_replace("'", "''''", $res->Value);

                   $dataAccess->Command->CommandText = 'CALL sp_Resources_Translate(\''.$to.'\',\''.$res->Code.'\',\''.$newValue.'\')';

                   if(!$dataAccess->Command->ExecuteNonQuery())
                   {

                        $error = $dataAccess->Command->Connection->error;

                        printf('ERR:The following error occurred while accessing the database: %s <br />', $error);

                   }

               }

               $dataAccess->Cleanup();

               if (isset($error))
               {

                   return 'An error occurred during the translation process.';

               }
               else
               {

                   return 'Translation succeeded.';

               }

            }
            catch (Exception $e)
            {

                return 'Exception: ' . $e->getMessage() . PHP_EOL;

            }

        }

    }

?>
